返回的IEnumerable< T> VS IQueryable的< T> [英] Returning IEnumerable<T> vs IQueryable<T>

查看:126
本文介绍了返回的IEnumerable< T> VS IQueryable的< T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是返回的区别的IQueryable< T> VS 的IEnumerable< T>

What is the difference between returning IQueryable<T> vs IEnumerable<T>?

IQueryable<Customer> custs = from c in db.Customers
where c.City == "<City>"
select c;

IEnumerable<Customer> custs = from c in db.Customers
where c.City == "<City>"
select c;

都将推迟执行,当一个人应该pferred比其他$ P $?

Will both be deferred execution and when should one be preferred over the other?

推荐答案

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

Yes, both will give you deferred execution.

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

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.

这篇关于返回的IEnumerable&LT; T&GT; VS IQueryable的&LT; T&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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