Home

Processing Arrays in C# by Using foreach

|
|  Updated:  
2018-01-26 13:55:05
C# 2010 All-in-One For Dummies
Explore Book
Buy On Amazon
C# variables that contain single values are plenty useful. Even class structures that can describe compound objects made up of parts are critical. But you also need a construct for holding a bunch of objects.The built-in class Array is a structure that can contain a series of elements of the same type.

Given an array of strings, the following loop averages their lengths:

public class Student // Read about classes in Book II.

{

public string name;

public double gpa; // Grade point average

}

public class Program

{

public static void Main(string[] args)

{

// . . .create the array somehow . . .

// Now average the students you have.

double sum = 0.0;

<strong> </strong>for (int i = 0; i < students.Length; i++)

{

sum += students[i].gpa;

}

double avg = sum / students.Length;

// . . .do something with the average . . .

}

}

The for loop iterates through the members of the array. (Yes, you can have arrays of any sort of object, not just of simple types such as double and string.) students.Length contains the number of elements in the array.

C# provides another loop, named foreach, designed specifically for iterating through collections such as the array. It works this way:

// Now average the students that you have.

double sum = 0.0;

foreach (Student student in students)

{

sum += student.gpa; // This extracts the current student’s GPA.

}

double avg = sum / students.Length;

The first time through the loop, foreach fetches the first Student object in the array and stores it in the variable student. On each subsequent pass, foreach retrieves the next element. Control passes out of the foreach loop when all elements in the array have been processed.

Notice that no index appears in the foreach statement. The lack of an index greatly reduces the chance of error and is simpler to write than the for statement, although sometimes that index is handy and you prefer a for loop.

The foreach loop is even more powerful than it would seem from the example. This statement works on other collection types in addition to arrays. In addition, foreach handles multidimensional arrays (arrays of arrays, in effect), a topic I don’t describe in this book. To find out all about multidimensional arrays, look up multidimensional arrays in the C# Language Help Index.

About This Article

This article is from the book: 

About the book author:

John Paul Mueller is a freelance author and technical editor. He has writing in his blood, having produced 100 books and more than 600 articles to date. The topics range from networking to home security and from database management to heads-down programming. John has provided technical services to both Data Based Advisor and Coast Compute magazines.

Bill Sempf is a seasoned programmer and .NET evangelist specializing in .NET applications.

Chuck Sphar is a programmer and former senior technical writer for the Visual C++ product group at Microsoft.