为什么将Count与IQueryable一起使用被认为是不可行的 [英] Why using Count with IQueryable is considered unfeasible

查看:342
本文介绍了为什么将Count与IQueryable一起使用被认为是不可行的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有以下代码:-

IQueryable<People> list = repository.FindAllPeople;  
int count = list.Count(); 

然后认为对IQueryable对象进行计数是不可行的,而最好使用IEnumerable? BR

Then is it considered as unfeasible to count IQueryable objects and it is better to use IEnumerable? BR

推荐答案

您被误导了.

IEnumerable将对对象使用Linq,所有方法都在内存中的对象 上执行. -IQueryable将使用特定提供程序提供的Linq扩展方法的任何实现.在这种情况下(存储库),我想它很可能是将Linq表达式映射到数据库语句的提供程序.

IEnumerable will use Linq to objects, all methods are executed on objects in memory. - IQueryable will use whatever implementation of the Linq extension methods is provided by the specific provider. In this case (a repository) I would guess it is most likely a provider that maps the Linq expressions to database statements.

这意味着如果您使用IQueryable:

IQueryable<People> list = repository.FindAllPeople;  
int count = list.Count(); 

该计数是在数据库本身上确定的,即作为查询"select count(*) from People".这通常非常非常快.

The count is determined on the database itself, i.e. as a query "select count(*) from People". This is usually very, very fast.

如果使用IEnumerable:

IEnumerable<People> list = repository.FindAllPeople;  
int count = list.Count(); 

在对对象的Linq正在遍历集合以确定计数时,所有People实例将被一个一个地实例化到内存中.这将非常缓慢,应尽可能避免.

All People instances will be materialized to memory one by one while Linq to objects is iterating through the collection to determine the count. This will be very slow and should be avoided whenever possible.

由于并非所有方法调用都可以映射到数据库查询,因此有时不可避免地要使用IEnumerable,但是如果可能的话,所有过滤,联接和分组都应在IQueryable上完成,那么作为最后一步,您可以使用AsEnumerable()扩展方法可以切换为使用IEnumerable和Linq来处理对象.

Since not all method calls can be mapped to database queries it is sometimes unavoidable to use an IEnumerable, but all filtering, joining and grouping should be done on an IQueryable if possible, then as a last step you can use the AsEnumerable() extension methods to switch to using IEnumerable and Linq to objects.

这篇关于为什么将Count与IQueryable一起使用被认为是不可行的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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