views:

388

answers:

2

Is there a reason why I can't do the following:

foreach (var Item in DataTable.Rows) {

rather than having to do

foreach (DataRow Item in DataTable.Rows) {

I would have thought this was possible, like it is on other datatypes. For example:

foreach (var Employee in Staff) { // string[] Staff etc...

When I try the first foreach loop, I get the the error CS0021: Cannot apply indexing with [] to an expression of type 'object'.

Why can't the compiler figure out that .Rows returns a collections of DataRows?

+10  A: 

Rows effectively returns IEnumerable (DataRowCollection), so the compiler can only pick object as the type for var. Use Rows.Cast<DataRow> if you want to use var.

Cast is defined on Enumerable, so you have to include System.Linq.

Brian Rasmussen
Were datatables before generics?
Arnis L.
@Arnis: Absolutely, DataTable has been in since 1.0.
Jon Skeet
So - i guess that's the real reason. Ty Jon for clarification. :)
Arnis L.
Thanks for the answer but I'm unable to get Rows.Cast<DataRow> to work. Would it be possible to give a quick foreach loop example?
GateKiller
@GateKiller: Did you include System.Linq? http://msdn.microsoft.com/en-us/library/bb341406.aspx
Brian Rasmussen
@GateKiller: When you say that you can't get something to work, it would be really helpful if you could say in what way it's not working. What error are you getting? Does it not compile, or run? You realise it's a method, so it'll be along the lines of "foreach (var row in DataTable.Rows.Cast<DataRow>())" right?
Jon Skeet
I've worked out that this requires Linq. Thanks for the answer :)
GateKiller
+9  A: 

Brian is absolutely right about the reason for this, but there's a simpler way of avoiding it: use DataTableExtensions.AsEnumerable():

foreach (var row in DataTable.AsEnumerable())
{
    ...
}
Jon Skeet
Thank you for such a nifty solution :) I have kept the Accepted Answer as Brian's but will be using yours. It's time a read up about Enumerables a bit more...
GateKiller
I'd say the real solution to the problem would be to not use var in this instance...
ck
@ck: Agreed, but it's worth knowing about `AsEnumerable` in order to tie in with other LINQ methods.
Jon Skeet
Good point Jon.
Brian Rasmussen