C#:遍历数据表:Rows,Select()或AsEnumerable() [英] 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)
有什么区别吗?
推荐答案
Rows
的类型不强-因此每次迭代都会进行强制类型转换,并且您不能对对象使用LINQ轻松地.(我相信 AsEnumerable()
也必须在内部对每次迭代进行转换,但是至少您可以轻松地将其用于其他LINQ方法.)
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
需要构建一个数组,因此显然存在性能损失.
Select
needs to build an array, so there's obviously a performance penalty there.
我个人会使用 AsEnumerable()
,除非您想修改循环中的表,在这种情况下, Select
会预先构建一个数组实际上是一个优势.
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.
这篇关于C#:遍历数据表:Rows,Select()或AsEnumerable()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!