Iterate over the items in arrays and lists in C#

[example]

You can use a foreach loop to iterate over the items in arrays, lists, collections, and other objects that have a GetEnumerator method. These loops are often more convenient than for or while loops because you don’t need to worry about figuring out how many items are in the collection or when to stop iterating.

This example’s Form_Load event handler uses the following code to initialize two arrays, a list, and a dictionary.

// Make two arrays, a list, and a dictionary.
string[] fruits = 
{ 
    "Apple", 
    "Banana", 
    "Cherry" 
};
List<string> cookies = new List<string>() 
{ 
    "Chocolate Chip", 
    "Snickerdoodle", 
    "Peanut Butter" 
};
Dictionary<int, string> dict = new Dictionary<>()
{
    {1, "One"},
    {2, "Two"},
    {3, "Three"},
};
string[,] array2d =
{
    { "0, 0", "0, 1", "0, 2"},
    { "1, 0", "1, 1", "1, 2"},
};

The program then uses the following code to iterate over the items in the various collections.

// Iterate over the items in the arrays, list, and dictionary.
foreach (string fruit in fruits) lstFruits.Items.Add(fruit);
foreach (string cookie in cookies) lstCookies.Items.Add(cookie);
foreach (KeyValuePair<> pair in dict)
    lstDictionary.Items.Add(pair);
foreach (string item in array2d) lstRowColumn.Items.Add(item);

The first foreach loop is relatively straightforward. It uses the variable fruit, which is of type string because that’s the type of data in the fruits array. During the loop, the variable fruit takes on each of the values in the array. It takes the values in order and the code adds the values to the lstFruits ListBox.

The second loop similarly iterates over the items in the list cookies. The string variable cookie takes on each of the values in the list in turn and the loop’s code adds them to the lstCookies ListBox.

The third loop iterates over a Dictionary<int, string>. The values used by this loop are structs of the type KeyValuePair<int, string> and they contain the key and value pairs held by the dictionary. The code adds the pairs to the lstDictionary ListBox, which uses the structs’ ToString methods to display them. The ToString method returns the key and value in square brackets as shown in the picture.

The final loop iterates over the items in a two-dimensional array, something that many programmers don’t realize is possible. If you look closely at the picture, you’ll see that the loop enumerates the items in the array in row-major order. In other words, it lists the items in the first row first, then the items in the second row, and so forth.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in arrays, lists, syntax and tagged , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *