Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why using Count with IQueryable is considered unfeasible

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

like image 991
john Gu Avatar asked Feb 12 '12 02:02

john Gu


People also ask

How do you count in IQueryable?

Please use the Count() method. IQueryable<People> list = repository. FindAllPeople; int cnt = list. Count();

Why do we use IQueryable?

IQueryable is best to query data from out-memory (like remote database, service) collections. While query data from a database, IQueryable execute the select query on the server side with all filters. IQueryable is suitable for LINQ to SQL queries. IQueryable supports deferred execution.

Why we use IQueryable in LINQ?

The IQueryable interface inherits the IEnumerable interface so that if it represents a query, the results of that query can be enumerated. Enumeration causes the expression tree associated with an IQueryable object to be executed. The definition of "executing an expression tree" is specific to a query provider.

What is the difference between the IQueryable and IEnumerable?

The main difference between IEnumerable and IQueryable in C# is that IQueryable queries out-of-memory data stores, while IEnumerable queries in-memory data. Moreover, IQueryable is part of . NET's System. LINQ namespace, while IEnumerable is in System.


1 Answers

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.

like image 194
BrokenGlass Avatar answered Oct 13 '22 01:10

BrokenGlass