Tuesday, 1 October 2013

What is the difference between IEnumerable and IEnumerator?



Both IEnumerable<T> and IEnumerator<T> are help to loop through collections i.e List<T>, Array List etc.
IEnumerable<T> actually uses IEnumerator<T>. IEnumerable<T> has GetEnumerator () function which returns IEnumerator<T> collection.

IEnumerable<T>
IEnumerator<T>
IEnumerable<T> does not remember currently which row is currently iterating through.
IEnumerator <T> remember its currently cursor state.
If you loop sequentially through collections then best use is IEnumerable<T>.
If we pass collection from one method to another and required to remember current cursor position then best use is IEnumerator <T>.

Q. What is the difference between IEnumerable<T> and IQueryable<T>?
Ans:
IEnumerable<T>
IQueryable<T>
IEnumerable<T> exists in System.Collections Namespace.
IQueryable<T> exists in System.Linq Namespace.
While query data from database, IEnumerable<T>
execute select query on server side, load data in-memory on client side and then filter data.
While query data from database, IQueryable<T> execute select query on server side with all filters.
IEnumerable<T> is suitable for LINQ to Object and LINQ to XML queries.
IQueryable<T> is suitable for LINQ to SQL queries.
When you deal with in memory collections (like List<T>, Array List etc) then best use is IEnumerable<T>.
When you want to deal with Sql server, linq to sql, entity framework and other data sources which implemented iqueryable then best use is IQueryable<T>.

Q. What is IList<T>?
Ans:
  IList<T> is an interface.
  Lists and arrays implement IList<T>.
  When you want to pass array or List<T> to any method then IList<T> can be used to hold those values.  
  When method need to add, remove, clear elements from the collection? Use IList<T>.



No comments:

Post a Comment