views:

631

answers:

2

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?

+7  A: 

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.

Mark Byers
Yes, it's trivial to get a jagged array using LINQ, but a true 2D array is something else entirely.
Anthony Pegram
A: 

This is how you can select from multi-dimensional array

        var arr = new int[,]  
            {  
                {1, 2, 3},   
                {4, 5, 6},   
                {7, 8, 9}  
            };

        var arrVals =
            from int val in arr
             select val;

        foreach (var a in arrVals)
        {
            Debug.WriteLine(a);
        }

(it will show 1, 2, 3, 4, ...). You can rebuilt this code to select from DataTable if you need it. Is that what you needed?

Vitaly
He wants to turn something *into* a multi-dimensional array.
Anthony Pegram