Foreach Loop in C#

0

 

foreach loop in c#

In C#, the foreach loop is a control flow statement that allows you to iterate over a collection of items, such as an array or a list. It provides a simple and concise way to iterate over each item in the collection without having to write complex code.

In this article, we will discuss the foreach loop in C# and how to use it to iterate over collections.

What is the foreach loop in C#?

The foreach loop is a special type of loop that is used to iterate over collections of data. It is designed to work with collections that implement the IEnumerable interface, which allows it to enumerate the collection and iterate over each item in turn.

How to use the foreach loop in C#

Using the foreach loop in C# is straightforward. Here is the basic syntax:


foreach (var item in collection)
{
    // Do something with item
}

In this example, item is a temporary variable that holds the current item in the collection, and collection is the collection that you want to iterate over.

Here is an example of how to use the foreach loop to iterate over an array of strings:


string[] names = { "John", "Mary", "Tom", "Jane" };
foreach (string name in names)
{
    Console.WriteLine(name);
}

In this example, we define an array of strings named names and then use the foreach loop to iterate over each item in the array. For each iteration, the name variable holds the current item, which we then print to the console using the Console.WriteLine() method.

You can also use the foreach loop to iterate over other types of collections, such as lists or dictionaries. Here is an example of how to use the foreach loop to iterate over a list of integers:


List<int> numbers = new List<int>() { 1, 2, 3, 4 };
foreach (int number in numbers)
{
    Console.WriteLine(number);
}

In this example, we define a list of integers named numbers and then use the foreach loop to iterate over each item in the list.

The foreach loop in C# is a powerful tool that simplifies the process of iterating over collections. It is easy to use and provides a clean and concise way to work with collections of data. Whether you are working with arrays, lists, or other types of collections, the foreach loop is an essential tool that you should have in your C# toolbox.


Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !