Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

linq

datatable

foreach (DataRow row in myDataTable.Select())

foreach (DataRow row in myDataTable.AsEnumerable())

foreach (DataRow row in myDataTable.Rows)

Any differences?

like image 304
Andrew White Avatar asked Sep 06 '10 19:09

Andrew White


1 Answers

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.

like image 172
Jon Skeet Avatar answered Sep 30 '22 21:09

Jon Skeet