Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting a multi-dimensional array in LINQ [duplicate]

I have a task where I need to translate a DataTable to a two-dimensional array. That's easy enough to do by just looping over the rows and columns (see example below).

private static string[,] ToArray(DataTable table)
{
    var array = new string[table.Rows.Count,table.Columns.Count];

    for (int i = 0; i < table.Rows.Count; ++i)
        for (int j = 0; j < table.Columns.Count; ++j)
            array[i, j] = table.Rows[i][j].ToString();

    return array;
}

What I'd really like to do is use a select statement in LINQ to generate that 2D array. Unfortunately it looks like there is no way in LINQ to select a multidimensional array. Yes, I'm aware that I can use LINQ to select a jagged array, but that's not what I want.

Is my assumption correct, or is there a way to use LINQ to select a multi-dimensional array?

like image 662
mckhendry Avatar asked Apr 01 '10 18:04

mckhendry


1 Answers

I don't think it is possible. My reasoning is that Select and most other LINQ functions require that the collections they work on implement at least IEnumerable<T> for some T:

public static IEnumerable<TResult> Select<TSource, TResult>(
    this IEnumerable<TSource> source,
    Func<TSource, TResult> selector
)

A rectangular array doesn't implement IEnumerable<T> for any T so it can't be the return value of a Select function.

like image 154
Mark Byers Avatar answered Sep 22 '22 07:09

Mark Byers