Why using Count with IQueryable is considered unfeasible

非 Y 不嫁゛ 提交于 2019-12-10 02:06:23

问题


If I have the following code:-

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

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


回答1:


You have been misinformed.

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.

That means if you use IQueryable:

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

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

If you use IEnumerable:

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

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.

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.




回答2:


I'm not familiar with the infeasability of IQueryable, but this blog post seems to indicate that IQueryable is much more preferable to IEnumerable because IQueryable allows access to the underlying expression.

This may only be relevant in the case of a Where clause and not impact .Count().



来源:https://stackoverflow.com/questions/9245933/why-using-count-with-iqueryable-is-considered-unfeasible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!