How do you use the foreach statement in C#?

In C#, the foreach statement is used to iterate through the elements in a collection. Its syntax format is as follows:

foreach (var item in collection)
{
    // 迭代逻辑
}

In this case, “collection” refers to the set that needs to be iterated over, which can be an array, list, dictionary, or similar. “Item” represents each element in the set, and during each iteration, it is assigned the value of one element in the set.

Here is a simple example:

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

The output result is:

1
2
3
4
5

In the example above, we defined an integer array called numbers, and then used a foreach statement to iterate through each element in the array and output it to the console.

bannerAds