C#: Iterating through collections
In C#, collections are used to store a group of related objects. Some examples of collections are arrays, lists, dictionaries, and sets. To access and process the items in a collection, you can use the foreach
loop in C#.
The foreach
Loop
The foreach
loop is used to iterate through each item in a collection. Here's an example using an array:
csharpint[] numbers = { 1, 2, 3, 4, 5 };
foreach (int number in numbers)
{
Console.WriteLine(number);
}
In the code above, we declared an array of integers called numbers
and used the foreach
loop to iterate through each item in the array. The foreach
loop consists of two parts: the type of the item (int number
) and the collection to iterate through (numbers
).
The foreach
loop is a convenient way to iterate through collections because it automatically keeps track of the current item and moves to the next item in the collection until there are no more items.
In conclusion, the foreach
loop in C# is a powerful tool for iterating through collections. By using the foreach
loop, you can process each item in a collection and perform operations on them efficiently and easily.