DEV Community

Discussion on: When should one choose IQueryable or IEnumerable?

Collapse
 
jamesmh profile image
James Hickey

IQueryable is specifically when you want to query your database using LINQ. That's pretty much it.

Really, you should never be returning anything with IQueryable but only using existing APIs that expose some IQueryable compatible methods (like EF). And then returning the results as IEnumerable.

Collapse
 
imlaguiar profile image
Leonardo Aguiar

I never return anything to the front-end with IQueryable, if that's what you meaning. But internally, like from a Repository to a Controller, wouldn't it be better to return an IQueryable object?

Suppose my controller calls a repository method to query over a database and return only the objects based on some filter, the repository returns the IQueryable object and then the controller checks if the object is empty, if it is not, it returns the object.ToList(). Would that be better in terms of performance?

Collapse
 
jamesmh profile image
James Hickey • Edited

No, it wouldn't be better performance overall because you still have to "do" the database query in order to check whether there are any rows.

Also, exposing repository methods where you might further "chain" them sounds like a good idea at first (performance, composability, etc.). But it becomes harder to reason about when you are mixing and chaining multiple methods.

Ideally, you should have a repo method that does the one thing you need. If that involves having to do multiple SQL queries then that one method should do them. So performance isn't an issue (actually, it could be better in this scenario) and it's very explicit as to what your code is doing.

E.g. you might have a method called GetUsersForProductXHavingPendingOrders

You could make that into two methods: GetUsersForProductX and GetUsersHavingPendingOrders, but the one combined method is more explicit and under the covers can implement whatever performance "tricks" needed.

In the end, IQueryable is really only for LINQ-to-SQL providers to use.