Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use AsQueryable() instead of List()?

I'm getting into using the Repository Pattern for data access with the Entity Framework and LINQ as the underpinning of implementation of the non-Test Repository. Most samples I see return AsQueryable() when the call returns N records instead of List<T>. What is the advantage of doing this?

like image 662
Keith Adler Avatar asked Jul 09 '09 22:07

Keith Adler


People also ask

Why do we use AsQueryable () on collection?

AsQueryable is a method that allow the query to be converted to an instance of IQueryable. When you use AsQueryable operator on an existing query and apply further transformations such as applying a filter or specifying a sort order, those lambda statements are converted to Expression trees.

What is the use of AsQueryable in LINQ?

Remarks. If the type of source implements IQueryable<T>, AsQueryable(IEnumerable) returns it directly. Otherwise, it returns an IQueryable<T> that executes queries by calling the equivalent query operator methods in Enumerable instead of those in Queryable.

What is the difference between AsEnumerable and AsQueryable?

AsEnumerable preserves deferred execution and does not build an often useless intermediate list. On the other hand, when forced execution of a LINQ query is desired, ToList can be a way to do that. AsQueryable can be used to make an enumerable collection accept expressions in LINQ statements.

Is IQueryable faster than list?

Here is a test that i have setup this evening. It was made to prove something different, but the outcome was not quite as i expected. I'm running a test with 10000 random queries on an IQueryable and while testing i found out that if i do the same on a List, my test is 20 times faster.


1 Answers

AsQueryable just creates a query, the instructions needed to get a list. You can make futher changes to the query later such as adding new Where clauses that get sent all the way down to the database level.

AsList returns an actual list with all the items in memory. If you add a new Where cluse to it, you don't get the fast filtering the database provides. Instead you get all the information in the list and then filter out what you don't need in the application.

So basically it comes down to waiting until the last possible momment before committing yourself.

like image 74
Jonathan Allen Avatar answered Sep 30 '22 18:09

Jonathan Allen