1

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,

2
  • 1
    Why? if you think about it, a DataTable is just a glorified array. Commented Jul 20, 2014 at 19:57
  • Probably, because I have not thought about it. Thank you, Steve! Commented Jul 20, 2014 at 20:00

1 Answer 1

1

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.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.