在没有Foreach循环的LINQ结果中访问行?

soo*_*ise 2 c# linq

对于我编写的每个LINQ查询,我总是使用foreach循环来完成结果.现在,我有一个程序,我想获得结果的前50行,用这些行做一些计算,然后得到接下来的50行结果等.

使用LINQ和C#执行此操作的好标准方法是什么?

Jus*_*ner 5

.Skip().在这种情况下,Take()将是最好的方法(就清晰度而言).例如:

var results = db.Table.Select(); // Your query here

int rowCount = results.Count(); // Count rows once and store

for(int i = 0; i <= rowCount; i += 50)
{
    var paged = results.Skip(i).Take(50);

    // do the calculations with the groups of 50 here
}
Run Code Online (Sandbox Code Playgroud)

值得注意的是,即使这看起来更清楚(你从结果中取出50个组),每次调用Skip()和Take()时,都有可能再次枚举集合......这实际上比单纯使用一次foreach枚举结果效率低.

  • 如果对象是"IEnumerable <>",这将遍历集合几次 (3认同)