在C#中,您可以使用多种方式来遍历数据结构,如数组、列表、字典等。以下是几种常见的方法:
int[] numbers = {1, 2, 3, 4, 5};
for (int i = 0; i < numbers.Length; i++) {
Console.WriteLine(numbers[i]);
}
或者使用foreach循环:
int[] numbers = {1, 2, 3, 4, 5};
foreach (int number in numbers) {
Console.WriteLine(number);
}
Dictionary<string, int> dictionary = new Dictionary<string, int>() {
{"apple", 1 }, {"banana", 2 }, {"cherry", 3 }
};
foreach (KeyValuePair<string, int> pair in dictionary) {
Console.WriteLine($"Key: {pair.Key}, Value: {pair.Value}");
}
C#中的LINQ(Language-Integrated Query)语言集成查询功能可以使遍历数据变得更加简单和强大。例如,您可以使用它筛选出列表中的偶数:
List<int> numbers = new List<int>() {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
var evenNumbers = from num in numbers
where num % 2 == 0
select num;
foreach (int num in evenNumbers)
{
Console.WriteLine(num);
}