相关疑难解决方法(0)

在LINQ查询上缓慢的foreach() - ToList()极大地提升了性能 - 为什么会这样?

我有点把握整个延迟执行的概念,但以下让我感到困惑......

在包含大约1000行的DataTable上,我调用了AsEnumerable().然后我选择返回到强类型类的IEnumerable中的实体(1) ......这就是我感到困惑的地方:我在集合上做了一个foreach循环; 使用一堆Where()调用(2)从集合中的各个项目中选择东西......而且它已经慢了.

  1. DataTable.AsEnumerable().Select(r => new ObjectRepresentation { ... });
  2. item.Where(i => i.SomeEnum == SomeEnum.Something)


...但是如果我在DataTable上调用AsEnumerable()之后立即调用ToList(),则foreach循环只需不到一秒钟即可完成.

我在这里错过了什么?每次我的循环迭代时,我是否有效地调用AsEnumerable()?或者每次我访问集合中的项目?或者每次我对集合中的项目进行Where()调用?或者以上所有?


更新

一些完整的代码:

public class ObjectRepresentation
{
    public SomeEnum SomeEnum { get; set; }
}


var collection = DataTable.AsEnumerable().Select(r => new ObjectRepresentation
{
    SomeEnum = (SomeEnum)Convert.ToInt32(r["SomeEnum"])
});

foreach(var item in collection) // slow loop
{
    // 10 or so Where() calls on item inside this loop
}

collection …
Run Code Online (Sandbox Code Playgroud)

c# linq

12
推荐指数
2
解决办法
7294
查看次数

标签 统计

c# ×1

linq ×1