#1,115 – Iterating Through a Collection Using the foreach Statement
June 11, 2014 2 Comments
In the same way that you can iterate through an array using foreach, you can iterate through the elements of a collection one at a time. You do this by writing a loop–a block of code that is executed more than once, executing once for each element in the collection. This is done using the C# foreach statement.
The foreach statement declares a variable local to the loop of the same type of the elements in the collection. This variable takes on the value of each element in the collection.
List<Dog> myDogs = new List<Dog> { new Dog {Name = "Kirby", Age = 15}, new Dog {Name = "Jack", Age = 17}, new Dog {Name = "Ruby", Age = 2} }; // Output using overridden ToString() method foreach (Dog d in myDogs) Console.WriteLine(d);