Jul 31, 2015

IEnumerable vs. ICollection vs. IQueryable vs. IList

Collections are used quite often in applications and C# have different types of collection. Here are the subtle differences between collection types and choose appropriate type based on your needs.
IEnumerable: Provides Enumerator for accessing collection
  • Used where you want to store a collection of objects which will be accessed only for read-only purpose.
  • You need to iterate through the collection, means to access an element at position 5 you first need to access 0-4 objects.
  • Cannot modify the list i.e. add, remove object operations not allowed.
ICollection:
  • List can be modified and iterated i.e. read, add, delete, edit operation allowed.
  • Operations like Sort are not allowed
IQueryable:
  • a special type because it allows deferred query execution i.e. if you define any query over IQueryable collection then it won’t execute till the time GetEnumerator() is called.
  • It is particularly used for Linq queries and in Entity Framework.
  • All other collection types brings data from the database to the client side and then apply filter or do operation on that data. However, IQueryable filters data at database level i.e. filtered data is received from database.
  • Specific example, In Entity Framework based application, you use IQueryable collection for seed data and if you call collection.SaveChanges() then database update command is not sent directly in fact when you will first try to access the data (or first time you call GetEnumerator on DBContext) then database update commands will be sent by entity framework. Good example of deferred query execution.
IList:
  • Used where you need to iterate (read), modify and sort, order a collection
  • Random element access allowed i.e. you can directly access an element at index 5 instead of first iterating through 0-4 elements.
These are the major differences between collection types and to explore more please visit following mentioned MSDN documentation.

No comments:

Post a Comment