且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

返回的IEnumerable< T> VS IQueryable的< T>

更新时间:2022-04-27 15:21:43

是的,既会给你延迟执行。

Yes, both will give you deferred execution.

不同的是,的IQueryable< T> 是允许LINQ到SQL(LINQ.到什么真正的)工作的接口。所以,如果你进一步细化上的的IQueryable&LT查询; T> ,该查询将在数据库中,如果可能的话执行。

The difference is that IQueryable<T> is the interface that allows LINQ-to-SQL (LINQ.-to-anything really) to work. So if you further refine your query on an IQueryable<T>, that query will be executed in the database, if possible.

对于的IEnumerable&LT; T&GT; 的情况下,这将是LINQ到对象,这意味着匹配原始查询的所有对象必须被加载到内存从数据库。

For the IEnumerable<T> case, it will be LINQ-to-object, meaning that all objects matching the original query will have to be loaded into memory from the database.

在code:

IQueryable<Customer> custs = ...;
// Later on...
var goldCustomers = custs.Where(c => c.IsGold);

这code将执行SQL,只选择黄金客户。下面code,另一方面,将执行在数据库中的原始查询,然后在存储器中过滤掉所述非金客户:

That code will execute SQL to only select gold customers. The following code, on the other hand, will execute the original query in the database, then filtering out the non-gold customers in the memory:

IEnumerable<Customer> custs = ...;
// Later on...
var goldCustomers = custs.Where(c => c.IsGold);

这是一个很重要的区别,并在的IQueryable&LT工作; T&GT; 能在许多情况下,节省您从数据库返回过多的行。另一个典型的例子是做分页:如果您使用跳过的IQueryable ,你只会得到要求的行数;这样做,在I 可枚举&LT; T&GT; 将导致所有的行的内存中加载

This is quite an important difference, and working on IQueryable<T> can in many cases save you from returning too many rows from the database. Another prime example is doing paging: If you use Take and Skip on IQueryable, you will only get the number of rows requested; doing that on an IEnumerable<T> will cause all of your rows to be loaded in memory.