Question

I have one 2D array:

string[,] table = new string[100,2];

and I want to add the table[,0] to a listbox, something like that

listbox1.Items.AddRange(table[,0]);

What is the trick to do that?

Edit: I want to know if it possible to do that using AddRange

Was it helpful?

Solution

For readability you can create extension method for an array.

public static class ArrayExtensions
{
    public static T[] GetColumn<T>(this T[,] array, int columnNum)
    {
        var result = new T[array.GetLength(0)];

        for (int i = 0; i < array.GetLength(0); i++)
        {
            result[i] = array[i, columnNum];
        }
        return result;
    }
}

Now you can easily add ranges as slices from array. Note that you create a copy of elements from original array.

listbox1.Items.AddRange(table.GetColumn(0));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top