返回 IEnumerable<T>与 IQueryable<T>

Returning IEnumerablelt;Tgt; vs. IQueryablelt;Tgt;(返回 IEnumerablelt;Tgt;与 IQueryablelt;Tgt;)
本文介绍了返回 IEnumerable<T>与 IQueryable<T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

返回 IQueryable<T>IEnumerable<T> 有什么区别,什么时候应该优先选择另一个?

What is the difference between returning IQueryable<T> vs. IEnumerable<T>, when should one be preferred over the other?

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;

两者都会被推迟执行,什么时候应该优先于另一个?

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

推荐答案

是的,两者都会给你 延迟执行.

Yes, both will give you deferred execution.

区别在于 IQueryable<T> 是允许 LINQ-to-SQL(LINQ.-to-anything)工作的接口.因此,如果您在 IQueryable<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<T> 情况下,它将是 LINQ-to-object,这意味着与原始查询匹配的所有对象都必须从数据库加载到内存中.

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.

在代码中:

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

该代码将执行 SQL 以仅选择黄金客户.另一方面,下面的代码会在数据库中执行原始查询,然后过滤掉内存中的非黄金客户:

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<T> 在很多情况下可以避免从数据库返回太多行.另一个主要示例是进行分页:如果您使用 Take跳过IQueryable,你只会得到请求的行数;在 IEnumerable<T> 上执行此操作将导致您的所有行都加载到内存中.

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;与 IQueryable&lt;T&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)