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

1 Answer 1

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));
Sign up to request clarification or add additional context in comments.

3 Comments

I just interest how I can add first column of 2d array to a listbox using AddRange function
so i can do it only by making my own function... ok thank you
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.