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
Please use the Count() method. IQueryable<People> list = repository. FindAllPeople; int cnt = list. Count();
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With