LINQ是否经过惰性评估? [英] Is LINQ lazy-evaluated?

查看:79
本文介绍了LINQ是否经过惰性评估?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问候,我有以下问题.我没有找到确切的答案,这对我来说真的很有趣.假设我有以下代码从数据库检索记录(例如,为了将其导出到XML文件).

Greetings, I have the following question. I did not find the exact answer for it, and it's really interesting to me. Suppose I have the following code that retrieves the records from database (in order to export it to XML file, for example).

var result = from emps in dc.Employees
  where emps.age > 21
  select emps;

foreach (var emp in result) {
  // Append this record in suitable format to the end of XML file
}

假设有一百万条满足代码中 where 条件的记录.会发生什么?当到达 foreach 构造时,所有这些数据将立即从SQL Server检索到运行时内存,或者将在必要时从第一条记录中检索出第二条记录.换句话说,LINQ是否真的通过遍历大量集合来处理这种情况(请参阅我的

Suppose there is a million of records that satisfy the where condition in the code. What will happen? All this data will be retrieved from SQL Server immediately to the runtime memory when it reaches the foreach construct, or it will be retrieved then necessary, the first record, second. In other words, does LINQ really handle the situation with iterating through large collections (see my post here for details)?

如果没有,在这种情况下如何克服内存问题?如果我真的需要遍历大量收藏,该怎么办?借助Count函数计算集合中元素的实际数量,然后一小部分从数据库中读取数据.有没有一种简单的方法可以使用LINQ框架实现分页?

If not, how to overcome the memory issues in that case? If I really need to traverse the large collection, what should I do? Calculate the actual amount of elements in collection with help of Count function, and after that read the data from the database by small portions. Is there an easy way to implement paging with LINQ framework?

推荐答案

所有数据将一次从SQL Server中检索,并放入内存中.我能想到的解决此问题的唯一方法是以较小的块处理数据(例如使用Skip()和Take()的页面).但是,当然,这需要对SQL Server进行更多的点击.

All the data will be retrieved from SQL Server, at one time, and put into memory. The only way around this that I can think of is to process data in smaller chunks (like page using Skip() and Take()). But, of course, this requires more hits to SQL Server.

这是我为此编写的Linq分页扩展方法:

Here is a Linq paging extension method I wrote to do this:

public static IEnumerable<TSource> Page<TSource>(this IEnumerable<TSource> source, int pageNumber, int pageSize)
    {
        return source.Skip((pageNumber - 1) * pageSize).Take(pageSize);
    }

这篇关于LINQ是否经过惰性评估?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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