如何在C#中使用foreach循环?


在C#中,foreach循环用于遍历集合或数组中的元素。它是一种简单而方便的循环结构,可以避免使用传统的for循环时可能出现的一些错误。

以下是使用foreach循环的语法:

foreach (var item in collection)
{
    // 执行操作
}

其中,collection是要遍历的集合或数组,item是当前迭代的元素。在循环体中,可以执行任何操作,例如打印元素或对元素进行计算。

以下是一个使用foreach循环遍历数组的示例:

int[] numbers = { 1, 2, 3, 4, 5 };
foreach (int num in numbers)
{
    Console.WriteLine(num);
}

输出:

1
2
3
4
5

还可以在foreach循环中使用LINQ查询,例如:

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
var evenNumbers = from num in numbers
                  where num % 2 == 0
                  select num;
foreach (int num in evenNumbers)
{
    Console.WriteLine(num);
}

输出:

2
4


About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.