在 Linq 中使用 IQueryable [英] Using IQueryable with Linq

查看:26
本文介绍了在 Linq 中使用 IQueryable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

IQueryable 在 LINQ 上下文中有什么用?

What is the use of IQueryable in the context of LINQ?

是用于开发扩展方法还是其他目的?

Is it used for developing extension methods or any other purpose?

推荐答案

Marc Gravell 的回答 非常完整,但我想我会从用户的角度添加一些关于此的内容......

Marc Gravell's answer is very complete, but I thought I'd add something about this from the user's point of view, as well...

从用户的角度来看,主要区别在于,当您使用 IQueryable(使用正确支持事物的提供程序)时,您可以节省大量资源.

The main difference, from a user's perspective, is that, when you use IQueryable<T> (with a provider that supports things correctly), you can save a lot of resources.

例如,如果您正在使用许多 ORM 系统处理远程数据库,您可以选择以两种方式从表中获取数据,一种返回 IEnumerable,和一个返回 IQueryable.举例来说,您有一个 Products 表,您想获取成本 > 25 美元的所有产品.

For example, if you're working against a remote database, with many ORM systems, you have the option of fetching data from a table in two ways, one which returns IEnumerable<T>, and one which returns an IQueryable<T>. Say, for example, you have a Products table, and you want to get all of the products whose cost is >$25.

如果你这样做:

 IEnumerable<Product> products = myORM.GetProducts();
 var productsOver25 = products.Where(p => p.Cost >= 25.00);

这里发生的是,数据库加载所有产品,并将它们通过线路传递给您的程序.然后您的程序过滤数据.本质上,数据库执行一个SELECT * FROM Products,并将每个产品返回给您.

What happens here, is the database loads all of the products, and passes them across the wire to your program. Your program then filters the data. In essence, the database does a SELECT * FROM Products, and returns EVERY product to you.

另一方面,使用正确的 IQueryable 提供程序,您可以:

With the right IQueryable<T> provider, on the other hand, you can do:

 IQueryable<Product> products = myORM.GetQueryableProducts();
 var productsOver25 = products.Where(p => p.Cost >= 25.00);

代码看起来一样,但这里的区别在于执行的 SQL 将是 SELECT * FROM Products WHERE Cost >= 25.

The code looks the same, but the difference here is that the SQL executed will be SELECT * FROM Products WHERE Cost >= 25.

从您作为开发人员的 POV 来看,这看起来是一样的.但是,从性能的角度来看,您只能通过网络返回 2 条记录,而不是 20,000 条......

From your POV as a developer, this looks the same. However, from a performance standpoint, you may only return 2 records across the network instead of 20,000....

这篇关于在 Linq 中使用 IQueryable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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