Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a list<> to a multi-dimensional array?

Tags:

arrays

c#

.net

list

I have the following method signature:

public void MyFunction(Object[,] obj)

I create this object:

List<List<Object>> obj = new List<List<Object>>;

Is there an easy way I can convert this to an Object[,]?


UPDATE:

The fact is I like to use Lists because I can easily add a new item. Is there a way I can declare my List<> object to fit this need? I know the number of columns in my Object[,] but not the number of rows.

like image 779
Melursus Avatar asked Mar 24 '09 16:03

Melursus


2 Answers

No. In fact, these aren't necessarily compatible arrays.

[,] defines a multidimensional array. List<List<T>> would correspond more to a jagged array ( object[][] ).

The problem is that, with your original object, each List<object> contained in the list of lists can have a different number of objects. You would need to make a multidimensional array of the largest length of the internal list, and pad with null values or something along those lines to make it match.

like image 162
Reed Copsey Avatar answered Sep 23 '22 14:09

Reed Copsey


You're not going to get a very simple solution for this (i.e. a few lines). LINQ/the Enumerable class isn't going to help you in this case (though it could if you wanted a jagged array, i.e. Object[][]). Plain nested iteration is probably the best solution in this case.

public static T[,] To2dArray(this List<List<T>> list)
{
    if (list.Count == 0 || list[0].Count == 0)
        throw new ArgumentException("The list must have non-zero dimensions.");

    var result = new T[list.Count, list[0].Count];
    for(int i = 0; i < list.Count; i++)
    {
        for(int j = 0; j < list[i].Count; j++)
        {
            if (list[i].Count != list[0].Count)
                throw new InvalidOperationException("The list cannot contain elements (lists) of different sizes.");
            result[i, j] = list[i][j];
        }
    }

    return result;
}

I've included a bit of error handling in the function just because it might cause some confusing errors if you used it on a non-square nested list.

This method of course assumes that each List<T> contained as an element of the parent List is of the same length. (Otherwise you really need to be using a jagged array.)

like image 35
Noldorin Avatar answered Sep 25 '22 14:09

Noldorin