在没有Foreach循环的情况下访问LINQ结果中的行? [英] Accessing Rows In A LINQ Result Without A Foreach Loop?

查看:76
本文介绍了在没有Foreach循环的情况下访问LINQ结果中的行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我编写的每个LINQ查询,我总是使用foreach循环来遍历结果.现在,我有一个程序,要获取结果的前50行,对这些行进行一些计算,然后获取结果的后50行,等等.

For every single LINQ query I've written, I've always used a foreach loop to go through the result. Now, I have a program where I want to get the first 50 rows of the result, do some calculations with those rows, then get the next 50 rows of the result etc.

使用LINQ和C#做到这一点的最佳标准方法是什么?

What is the good standards way to do this using LINQ and C#?

推荐答案

.Skip().Take()将是最好的方法.例如:

.Skip().Take() is going to be the best method (as far as clarity goes) in this case. For example:

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
}

值得注意的是,即使这看起来更加清晰(您从结果中取出50个组),但是每次调用Skip()和Take()时,都有可能需要再次对集合进行枚举...实际上比简单地使用foreach一次枚举结果效率低.

It is worth noting that even though this seems more clear (you're taking groups of 50 from the results), each time you call Skip() and Take() there's a chance that the collection has to be enumerated over again...which is actually less efficient than simply using foreach to enumerate over the results a single time.

这篇关于在没有Foreach循环的情况下访问LINQ结果中的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆