C# 遍历集合
介绍
在C#编程中,集合(如数组、列表、字典等)是存储和操作数据的常用工具。遍历集合是指逐个访问集合中的每个元素,以便对其进行处理或分析。掌握集合遍历的技巧是编写高效、可维护代码的关键。
本文将介绍如何在C#中遍历不同类型的集合,并提供实际的代码示例和应用场景。
遍历数组
数组是C#中最基本的集合类型之一。我们可以使用for
循环或foreach
循环来遍历数组。
使用for
循环遍历数组
csharp
int[] numbers = { 1, 2, 3, 4, 5 };
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine(numbers[i]);
}
输出:
1
2
3
4
5
使用foreach
循环遍历数组
csharp
int[] numbers = { 1, 2, 3, 4, 5 };
foreach (int number in numbers)
{
Console.WriteLine(number);
}
输出:
1
2
3
4
5
提示
foreach
循环更简洁,适用于不需要索引的场景。而for
循环则适用于需要访问索引的情况。
遍历列表
列表(List<T>
)是C#中常用的动态集合类型。与数组类似,我们可以使用for
循环或foreach
循环来遍历列表。
使用foreach
循环遍历列表
csharp
List<string> fruits = new List<string> { "Apple", "Banana", "Cherry" };
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}
输出:
Apple
Banana
Cherry
使用for
循环遍历列表
csharp
List<string> fruits = new List<string> { "Apple", "Banana", "Cherry" };
for (int i = 0; i < fruits.Count; i++)
{
Console.WriteLine(fruits[i]);
}
输出:
Apple
Banana
Cherry
遍历字典
字典(Dictionary<TKey, TValue>
)是一种键值对集合。遍历字典时,我们可以访问键、值或键值对。
遍历字典的键
csharp
Dictionary<string, int> ages = new Dictionary<string, int>
{
{ "Alice", 25 },
{ "Bob", 30 },
{ "Charlie", 35 }
};
foreach (string name in ages.Keys)
{
Console.WriteLine(name);
}
输出:
Alice
Bob
Charlie
遍历字典的值
csharp
foreach (int age in ages.Values)
{
Console.WriteLine(age);
}
输出:
25
30
35
遍历字典的键值对
csharp
foreach (KeyValuePair<string, int> entry in ages)
{
Console.WriteLine($"{entry.Key} is {entry.Value} years old.");
}
输出:
Alice is 25 years old.
Bob is 30 years old.
Charlie is 35 years old.
实际应用场景
场景1:统计学生成绩
假设我们有一个学生成绩列表,我们需要计算平均分。
csharp
List<int> scores = new List<int> { 85, 90, 78, 92, 88 };
int sum = 0;
foreach (int score in scores)
{
sum += score;
}
double average = (double)sum / scores.Count;
Console.WriteLine($"Average score: {average}");
输出:
Average score: 86.6
场景2:查找最高分
我们可以遍历列表来找到最高分。
csharp
int maxScore = scores[0];
foreach (int score in scores)
{
if (score > maxScore)
{
maxScore = score;
}
}
Console.WriteLine($"Highest score: {maxScore}");
输出:
Highest score: 92
总结
遍历集合是C#编程中的基本操作,掌握不同的遍历方法可以帮助你更高效地处理数据。无论是数组、列表还是字典,C#都提供了灵活的遍历方式。通过本文的学习,你应该能够熟练使用for
循环和foreach
循环来遍历各种集合类型。
附加资源与练习
- 练习1:创建一个包含10个整数的列表,使用
foreach
循环计算它们的总和。 - 练习2:创建一个字典,存储城市名称和对应的人口数量,遍历字典并打印出人口超过100万的城市。
- 资源:查阅C#官方文档以了解更多关于集合和遍历的详细信息。
警告
在遍历集合时,注意不要在循环中修改集合的结构(如添加或删除元素),这可能会导致运行时错误。