EF ICollection Vs List Vs IEnumerable Vs IQueryable

Solution 1:

IQueryable:

  • Query isn't executed until you really iterate over the items, maybe by doing a .ToList() or a foreach. Which means you still can add filters, like a Where().
  • Extends IEnumerable

IEnumerable:

  • Forward-only list of items. You can't get at "item 4" without passing items 0-3.
  • Read-only list, you can't add to it or remove from it.
  • Still might use deferred execution (IQueryable is still an IEnumerable).

IList:

  • Random access to the full list
  • Probably entirely in memory (no deferred execution, but who knows what the exact class does that implements this?)
  • Supports adding and removing
  • Extends IEnumerable and ICollection

ICollection:

  • Is between IEnumerable and IList.
  • Extends IEnumerable

What is "best" depends on your requirements. Usually though an IEnumerable is "good enough" if you only want to display items. At least always use the generic variant.

Solution 2:

Another difference in case of EF is that the IEnumerable is not executing the query to the DB untill you really enumerate the list. While the IList will execute the query and fetch the items in memory. I had a strange behaviour with caching. Chaching the IEnumarable didn't store the items but rather the unfetched enumeration, everytime i would call the cache and fetch the enumeration for some purpose, it would go to the DB and execute the query, so caching was useless. But a ToList() on the enumeration fetched the items and stored the items in the cache, so only 1 trip to the DB for this. Find more in this post: http://www.dailycode.info/BlogV2/post/entityframework-adding-ienumerable-to-cache