Reputation: 7730
I have the following DataTable
ItemNumber Quantity Order
1 2 3
4 3 8
7 7 9
I would like to load first two columns into 2 dimensional array. If it is not possible, at least I would like to get first column into 1 dimension array.
Of course, I can write a loop, but I wonder if it is possible to avoid loops.
Regards,
Upvotes: 1
Views: 6535
Reputation: 13286
You won't necessarily be able to avoid loops in the technical sense, but you could write something like this:
DataTable table = ...;
return table.Rows.Cast<DataRow>().Select(c => new[] { c[0], c[1] });
That's an array of arrays, rather than a multidimensional array. But from what I've seen multidimensional arrays seem to be phased out as standard practice in most applications. You might also want to parse each row in that Select
to being some actual type.
If you leave this as an IEnumerable<>
, it will not need to loop more than the once that you use it, but if you're reading at random points a lot (using the indexer, or what have you), you might want to append .ToArray()
. That decision depends on how you're using it. As a general rule, it's nice to write code that doesn't depend on random access like that, since then you don't have to read from the DataTable
more than once per record.
Upvotes: 1