16

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?

2
  • Could you do an array of arrays instead? (it would be faster to convert) Commented Apr 1, 2010 at 19:08
  • Yes, I can do a jagged array (array of arrays), but unfortunately in this case that's not what the api I was calling would accept. Commented Apr 4, 2010 at 18:54

1 Answer 1

15

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, it's trivial to get a jagged array using LINQ, but a true 2D array is something else entirely.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.