#155 – Iterating Through an Array Using the foreach Statement

You can write a loop–a block of code that is executed more than once–that executes once for each element in an array, using the C# foreach statement.

The foreach statement declares a variable local to the loop of the same type of the elements in the array.  This variable takes on the value of each element in the array.

            Person[] folks = new Person[4];
        	folks[0] = new Person("Bronte", "Emily");
	        folks[1] = new Person("Bronte", "Charlotte");
	        folks[2] = new Person("Tennyson", "Alfred");
	        folks[3] = new Person("Mailer", "Norman");

            string sLastNameList = "";

            // For each Person in array, dump out name and concatenate last name
            foreach (Person p in folks)
            {
                Console.WriteLine("{0} {1}", p.FirstName, p.LastName);
                sLastNameList += p.LastName;
            }
Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #155 – Iterating Through an Array Using the foreach Statement

  1. Pingback: #583 – You Can’t Modify the Iterator Variable Within a foreach Loop « 2,000 Things You Should Know About C#

  2. Pingback: #1,116 – Iterating Through a String Using the foreach Statement | 2,000 Things You Should Know About C#

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 )

Connecting to %s

%d bloggers like this: