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:
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:
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:
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.