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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With