0

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

a1204773
  • 6,923
  • 20
  • 64
  • 94

1 Answers1

1

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));
Ilya Ivanov
  • 23,148
  • 4
  • 64
  • 90
  • I just interest how I can add first column of 2d array to a listbox using AddRange function – a1204773 Feb 03 '13 at 23:44
  • so i can do it only by making my own function... ok thank you – a1204773 Feb 03 '13 at 23:52
  • yes, there is nothing build in `.net` for this purposes. But you can use jagged arrays, which are essentially arrays of arrays, which in your canse would be `string[][]`. Then accessing `table[2]` will return to you the second row. – Ilya Ivanov Feb 03 '13 at 23:55