Pregunta

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

¿Fue útil?

Solución

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));
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top