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

本文是小编为大家收集整理的关于在没有Foreach循环的情况下访问LINQ结果中的行?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

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

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

推荐答案

.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
}

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

本文地址:https://www.itbaoku.cn/post/1556835.html

问题描述

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.

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

推荐答案

.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
}

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.

相关标签/搜索