Andrew White
Andrew White

Reputation: 1789

C#: Iterating through a data table: Rows, Select() or AsEnumerable()

foreach (DataRow row in myDataTable.Select())

foreach (DataRow row in myDataTable.AsEnumerable())

foreach (DataRow row in myDataTable.Rows)

Any differences?

Upvotes: 7

Views: 6867

Answers (2)

Brian Mains
Brian Mains

Reputation: 50728

Use AsEnumerable() if you are trying to query the datatable using LINQ, otherwise, you might as well use the looping structure...

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500495

Rows isn't strongly typed - so there will be a cast on each iteration, and you can't use LINQ to objects on it easily. (I believe AsEnumerable() will have to cast on each iteration internally as well, but at least you can use it for other LINQ methods easily.)

Select needs to build an array, so there's obviously a performance penalty there.

Personally I'd use AsEnumerable() unless you wanted to modify the table within the loop, in which case the fact that Select builds an array up-front may actually be an advantage.

Upvotes: 8

Related Questions