Loop over entries in an array of unknown length in C#


One way to loop through the items in an array is to hard code its length into the program. Alternatively you can use the array’s Length property to determine how many items it contains at runtime. Then if you later change the array’s length, or if the array is created at run time, you don’t need to update the looping bounds.

When it starts, this program uses the following code to loop through the items in a one-dimensional array and add them to a string.

// List a one-dimensional array's values.
string[] values1 = { "0", "1", "2", "3", "4" };
string txt = "";
for (int i = 0; i < values1.Length; i++)
    txt += " " + values1[i];
if (txt.Length > 0) txt = txt.Substring(1);
txtValues1.Text = txt;
txtValues1.Select(0, 0);

All arrays start with 0 as a lower bound in C# so the largest index in an array is the arra’s length minus 1. This code makes variable i loop from 0 to the array’s Length minus 1. (All arrays have 0 lower bounds unless you use the Array class’s CreateInstance method. See the example Make arrays with non-zero lower bounds in C#.)

There is one trick here worth mentioning. The loop adds a space before each item in the string so when the loop finishes there is an extra space before the first item (if there are any items at all) so the code removes it by using the Substring method.

Note that there are easier ways to concatenate values in an array. In this example, you could use String.Join(" ", values1). This example just shows how you could loop over the items and do something with them.

Also note that you could use a foreach loop to loop through the items in the array if you don’t care about their indices.

For multi-dimensional arrays, you can use the array’s GetLowerBound and GetUpperBound methods to determine how many items the array has in each dimension. For example, GetUpperBound(1) returns the largest value you can use for the array’s second index. (The index numbers also start at 0 so index 1 is the second.)

This example uses the following code to loop through the items in a two-dimensional array.

// List a two-dimensional array's values.
string[,] values2 =
    { "(0, 0)", "(0, 1)", "(0, 2)", "(0, 3)", "(0, 4)" },
    { "(1, 0)", "(1, 1)", "(1, 2)", "(1, 3)", "(1, 4)" },
    { "(2, 0)", "(2, 1)", "(2, 2)", "(2, 3)", "(2, 4)" }
txt = "";
for (int i = 0; i <= values2.GetUpperBound(0); i++)
    string line = "";
    for (int j = 0; j <= values2.GetUpperBound(1); j++)
        line += " " + values2[i, j];
    if (line.Length > 0) line = line.Substring(1);
    txt += Environment.NewLine + line;
if (txt.Length > 0) txt = txt.Substring(Environment.NewLine.Length);
txtValues2.Text = txt;
txtValues2.Select(0, 0);

The variable i loops over the array’s possible first indexes. As before the lower bound is 0. The code gets the array’s upper bound for the first dimension by calling GetUpperBound(0).

Inside the for i loop, the code makes variable j loop over the array’s possible second indexes, running from 0 to GetUpperBound(1).

Notice that the loops use <= instead of < for their stopping conditions. This is because an array’s Length property returns the total number of items so the index of the last item is one less than Length. in contrast the GetUpperBound method returns the largest index for a dimension, not one more than that index.

Notice also that this code uses the previous trick of adding separator characters (space or a new line) in front of items so it removes the separator that comes before the first item when it is done.

I know this is a fairly simple example, but the idea of making the code figure out the size of the array instead of hard-coding the bounds is important. It means you won’t need to revise the code if you change the size of the array later. (It also provides a preview for my next post, which is less straightforward.)

Download Example   Follow me on Twitter   RSS feed   Donate

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

Leave a Reply

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