The foreach loop

The foreach loop

The foreach loop in C# is used to iterate over elements in a collection, such as an array, a list, or a dictionary. It has the following syntax:

foreach (var item in collection)

{

    // code to execute

}

The collection is the collection that you want to iterate over, and item is a variable that represents the current element in the collection. The var keyword is used to declare the type of item implicitly. You can also use a specific data type instead of var.

Here’s an example of how to use the foreach loop to iterate over an array of integers:

int[] numbers = { 1, 2, 3, 4, 5 };

foreach (int number in numbers)

{

    Console.WriteLine(number);

}

In this example, the foreach loop iterates over each element in the numbers array, assigning each element to the variable number, and then executing the code inside the loop, which prints the value of number to the console.

You can also use the foreach loop to iterate over a dictionary:

Dictionary<string, int> dictionary = new Dictionary<string, int>

{

    {“apple”, 1},

    {“banana”, 2},

    {“cherry”, 3}

};

foreach (KeyValuePair<string, int> item in dictionary)

{

    Console.WriteLine(“Key: {0}, Value: {1}”, item.Key, item.Value);

}

In this example, the foreach loop iterates over each key-value pair in the dictionary, assigning each key-value pair to the variable item, and then executing the code inside the loop, which prints the key and value of each item to the console. The foreach loop is a convenient way to iterate over elements in a collection. It eliminates the need for you to manually manage the index of the current element, and it simplifies your code by removing the need for explicit initialization, condition, and increment statements.

Apply for ASP.NET Certification Now!!

https://www.vskills.in/certification/certified-aspnet-programmer

Back to Tutorial

Get industry recognized certification – Contact us

Menu