How to iterate through the elements of a collection using a foreach loop in C#?
How to iterate through the elements of a collection using a foreach loop in C#?
I completed my post-graduation in 2013 in the engineering field. Engineering is the application of science and math to solve problems. Engineers figure out how things work and find practical uses for scientific discoveries. Scientists and inventors often get the credit for innovations that advance the human condition, but it is engineers who are instrumental in making those innovations available to the world. I love pet animals such as dogs, cats, etc.
Aryan Kumar
05-Nov-2023In C#, you can iterate through the elements of a collection, such as a list, array, or other enumerable data structure, using a foreach loop. Here's how to do it:
Here's a step-by-step explanation:
foreach Loop: Start with the foreach keyword, followed by parentheses containing the loop variables and the collection to be iterated.
ElementType: Replace "ElementType" with the actual data type of the elements within the collection. This is the type of variable that will represent each element during iteration.
element: Choose a variable name (e.g., element) that will represent each element as you iterate through the collection. This variable is declared implicitly.
collection: Replace "collection" with the name of the collection you want to iterate through.
Here's an example of how to use a foreach loop to iterate through the elements of a list:
In this example, a List<int> named numbers is created and populated with integers. The foreach loop iterates through the elements of the list, and the variable number represents each element in turn. The code inside the loop body prints each element to the console.
You can use a foreach loop to iterate through various types of collections, such as arrays, lists, dictionaries, sets, and custom data structures that implement the IEnumerable or IEnumerable<T> interface. The foreach loop simplifies the process of iterating through elements and is widely used for working with collections in C#.