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

那年仲夏 提交于 2021-02-07 07:10:59

问题


foreach (DataRow row in myDataTable.Select())

foreach (DataRow row in myDataTable.AsEnumerable())

foreach (DataRow row in myDataTable.Rows)

Any differences?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/3653993/c-iterating-through-a-data-table-rows-select-or-asenumerable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!