#1,115 – Iterating Through a Collection Using the foreach Statement

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);
1115-001
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

2 Responses to #1,115 – Iterating Through a Collection Using the foreach Statement

  1. Pingback: Dew Drop – June 11, 2014 (#1795) | Morning Dew

  2. bclayshannon says:

    Cool, but let’s see the overridden ToString() method.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: