Dot Net Perls
C#

2D Array Use

by Sam Allen

Problem

You have a 2D array containing any type of value. We want to iterate through each element in it, using a for loop. You may not know the dimensions of the array: for example, it may have 2 items in each row, or any other number. An easy-to-maintain loop is required.

Solution: C#

Two-dimensional arrays are harder to deal with than 1D arrays, mainly because of the syntax in declaring them. They are different from jagged arrays, which are covered on this site separately. Let's look at how a two-dimensional array can be declared first, and then we will look at two ways of iterating through every element.

/// <summary>
/// This is an example class.
/// </summary>
static class Test2D
{
    static string[,] _testArray2D = new string[,] // Static just for example
    {
        {"ant", "aunt"},     // The first row in the 2D array.
        {"Sam", "Samantha"}, // The second... etc.
        {"clozapine", "quetiapine"},
        {"flomax", "volmax"},
        {"toradol", "tramadol"}
    };
}

How can I iterate through 2D arrays?

There are two options here. The first option is to use the GetUpperBound() method on the array. Here we will look at this option. Note however that this method is probably not the best for a simple 2D array, because it is very slow. Here is the first method.

for (int i = 0; i <= _testArray2D.GetUpperBound(0); i++)
{
    string a = _testArray2D[i, 0]; // First set to 'ant', then 'Sam', 'clozapine'
    string b = _testArray2D[i, 1]; // First set to 'aunt', then 'Samantha', 'quetiapine'
}

What is the fastest method?

The fastest method for a 2D array, according to my testing, is to do some arithmetic if you know the number of 'rows' in the array. In this example, there are 5 rows. GetUpperBound(0) will return 4 (the last index). However, if we take the Length, which is 10, and divide by 2, we get 5.

for (int i = 0; i < _testArray2D.Length / 2; i++)
{
    string a = _testArray2D[i, 0]; // ant, Sam, clozapine...
    string b = _testArray2D[i, 1]; // aunt, Samantha, quetiapine....
}

How slow is GetUpperBound?

Very slow and it could be a bottleneck in your code. What I have next here is a benchmark comparing 1 million repetitions of the above two loops with the array shown. This illustrates the performance problem with GetUpperBound. This leads me to recommend that you always use the Length / 2 method if possible.

Loop tested Time in ms
1 million iterations
GetUpperBound 140
Length / 2 47

Summary

Here is the syntax and methods for using 2D arrays in C# .NET. Clearly, it is best to find the length of the dimensions using Length if possible, but GetUpperBound can also be useful. 2D arrays can be set using the comma syntax. They are slower than jagged arrays, which use vectors in the runtime. Use them to your advantage.

© 2008 Sam Allen. All rights reserved.

Ads by The Lounge