IQueryable和IEnumerable有什么区别 [英] What's the difference between IQueryable and IEnumerable

查看:74
本文介绍了IQueryable和IEnumerable有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对区别感到困惑.作为.Net的新手,我知道我可以使用Linq扩展名查询IEnumerables.那么,IQueryable是什么,又有什么不同?

I'm confused as to the difference. Being fairly new to .Net, I know I can query IEnumerables using the Linq extensions. So what is this IQueryable and how does it differ?

另请参见 IQueryable [T]有什么区别和IEnumerable [T]?与此问题重叠.

See also What is the difference between IQueryable[T] and IEnumerable[T]? that overlaps with this question.

推荐答案

IEnumerable<T>表示T的仅向前游标. .NET 3.5添加了包括LINQ standard query operators在内的扩展方法,例如WhereFirst,并且任何需要谓词或匿名函数的运算符都采用Func<T>.

IEnumerable<T> represents a forward-only cursor of T. .NET 3.5 added extension methods that included the LINQ standard query operators like Where and First, with any operators that require predicates or anonymous functions taking Func<T>.

IQueryable<T>实现相同的LINQ标准查询运算符,但接受Expression<Func<T>>作为谓词和匿名函数. Expression<T>是已编译的表达式树,是该方法的分解版本(如果可以,则为半编译"),可以由查询对象的提供程序进行解析并相应地使用.

IQueryable<T> implements the same LINQ standard query operators, but accepts Expression<Func<T>> for predicates and anonymous functions. Expression<T> is a compiled expression tree, a broken-up version of the method ("half-compiled" if you will) that can be parsed by the queryable's provider and used accordingly.

例如:

IEnumerable<Person> people = GetEnumerablePeople();
Person person = people.Where(x => x.Age > 18).FirstOrDefault();

IQueryable<Person> people = GetQueryablePeople();
Person person = people.Where(x => x.Age > 18).FirstOrDefault();

在第一个块中,x => x.Age > 18是一个匿名方法(Func<Person, bool>),可以像其他任何方法一样执行. Enumerable.Where将为每个人执行一次该方法,并yield计算该方法返回的值true.

In the first block, x => x.Age > 18 is an anonymous method (Func<Person, bool>), which can be executed like any other method. Enumerable.Where will execute the method once for each person, yielding values for which the method returned true.

在第二个块中,x => x.Age > 18是一个表达式树(Expression<Func<Person, bool>>),可以将其视为是'Age'属性> 18".

In the second block, x => x.Age > 18 is an expression tree (Expression<Func<Person, bool>>), which can be thought of as "is the 'Age' property > 18".

这允许LINQ-to-SQL之类的东西存在,因为它们可以解析表达式树并将其转换为等效的SQL.而且由于提供程序不需要枚举IQueryable(毕竟实现了IEnumerable<T>),因此它可以组合多个查询运算符(在上面的示例WhereFirstOrDefault中)以使其更聪明选择如何对基础数据源执行整个查询(例如在SQL中使用SELECT TOP 1).

This allows things like LINQ-to-SQL to exist because they can parse the expression tree and convert it into equivalent SQL. And because the provider doesn't need to execute until the IQueryable is enumerated (it implements IEnumerable<T>, after all), it can combine multiple query operators (in the above example Where and FirstOrDefault) to make smarter choices on how to execute the entire query against the underlying data source (like using SELECT TOP 1 in SQL).

请参阅:

这篇关于IQueryable和IEnumerable有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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