4

I am querying a database and producing a list of object from it.

Normally from my business layer I return this list of objects cached of type IList. If I change this to return IQueryable, what is the advantage to such? What does IQueryable give me that IList does not?

amateur
  • 43,371
  • 65
  • 192
  • 320

4 Answers4

6

IQueryable is an interface that is used to query databases, and defines functionality that allows implementors to do neat things like deferred execution and construction of more optimized queries (via evaluating the expression tree). IList gives you none of that.

Furthermore, IQueryable is (for the most part) a read-only interface. IList defines Add, Remove, and so on that permit the user to modify the collection. If that makes more sense for you semantically, then by all means use that and then use the IEnumerable Linq extensions to get most of the functionality of IQueryable.

Patrick Quirk
  • 23,334
  • 2
  • 57
  • 88
1

I like to use IEnumerable for all return types - and I implement them with List in the method that returns it if they are simple, or a more specialized concrete class if I need to. The advantage is, I rarely, if ever need to change the client of the class implementing IEnumerable. I don't care if it is a List or a Hash table. With IList, you're stuck using a List.

However, if you're using LINQ-to-SQL, or you are working with large amounts of data in your class, IQueryable supports some methods IEnumerable does not. IEnumerable is the base implementation of ILIst and IQueryable, so that's why I recommend using that as your return type from most functions

Check out these articles for a good explanation of the difference between IQueryable and IEnumerable:

Returning IEnumerable<T> vs. IQueryable<T> and What is the difference between IQueryable<T> and IEnumerable<T>?

Community
  • 1
  • 1
Max Barfuss
  • 1,432
  • 2
  • 9
  • 14
0

If you are going to use to query the database then I think IQueryable is more useful. APrta from that, with IList you can add,remove, get specific item from list. It all depends on how you want to use it..

user1532976
  • 469
  • 2
  • 8
  • 15
0

You could return IEnumerable<T> and then cast to either to make it more flexible... But IQueryable<T> is better approach for execution where you would literally query the database. If you're wanting the ability to manipulate collections, I would choose IList<T>

Gabe
  • 49,577
  • 28
  • 142
  • 181