且构网

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

将IQueryable linq查询转换为IEnumerable< T>取消linq优化的工作方式?

更新时间:2023-02-14 10:52:01

它仍将在数据库中执行,请放心.基本上,这取决于使用Where等的实现.当您通过Queryable扩展方法在IQueryable<T>上调用方法时,它将使用表达式树.当您从该查询开始获取时,它将被转换为SQL并发送到数据库.

It's still going to execute in the database, don't worry. Basically it's all down to which implementation of Where etc is used. While you're calling methods on IQueryable<T> - via the Queryable extension methods - it will be using expression trees. When you start to fetch from that query, it will be turned into SQL and sent to the database.

另一方面,如果在之后使用任何这些方法,则将其作为IEnumerable<T>(就编译时类型而言),它将使用扩展方法在Enumerable中,其余所有处理 将在处理中完成.

On the other hand, if you use any of those methods after you've got it as an IEnumerable<T> (in terms of the compile-time type), that will use the extension methods in Enumerable, and all of the rest of the processing would be done in-process.

作为一个例子,考虑一下:

As an example, consider this:

var query = db.People
              .Where(x => x.Name.StartsWith("J"))
              .AsEnumerable()
              .Where(x => x.Age > 20);

此处AsEnumerable() just 返回其输入序列,但键入为IEnumerable<T>.在这种情况下,数据库查询将仅返回名称以J开头的人员-然后将在客户端进行年龄过滤.

Here AsEnumerable() just returns its input sequence, but typed as IEnumerable<T>. In this case, the database query would return only people whose name began with J - and then the age filtering would be done at the client instead.