C# Foreach Loop: Complete Guide with Examples

In C#, the foreach loop is used to iterate through elements in a collection or array. Here is an example of how to use the foreach loop statement:

// 使用foreach循环遍历数组
int[] numbers = { 1, 2, 3, 4, 5 };
foreach (int number in numbers)
{
    Console.WriteLine(number);
}

// 使用foreach循环遍历集合
List<string> names = new List<string> { "Alice", "Bob", "Charlie" };
foreach (string name in names)
{
    Console.WriteLine(name);
}

// 使用foreach循环遍历字符串中的字符
string str = "Hello";
foreach (char c in str)
{
    Console.WriteLine(c);
}

In the example above, we used a foreach loop to iterate through the elements in an array, a collection, and a string respectively. During each iteration of the loop, the loop variable (such as number, name, c) will successively access the elements in the collection or array, allowing for corresponding operations to be performed on them.

bannerAds