In LINQ to query data from collections, we use IEnumerable and IList for data manipulation.IEnumerable is inherited by IList, hence it has all the features of it and except this, it has its own features. IList has below advantage over IEnumerable.
IList
- IList exists in System.Collections Namespace.
- IList is used to access an element in a specific position/index in a list.
- Like IEnumerable, IList is also best to query data from in-memory collections like List, Array etc.
- IList is useful when you want to Add or remove items from the list.
- IList can find out the no of elements in the collection without iterating the collection.
- IList supports deferred execution.
- IList doesn't support further filtering.
IEnumerable
- IEnumerable exists in System.Collections Namespace.
- IEnumerable is a forward only collection, it can't move backward and between the items.
- IEnumerable is best to query data from in-memory collections like List, Array etc.
- IEnumerable doen't support add or remove items from the list.
- Using Ienumerable we can find out the no of elements in the collection after iterating the collection.
- IEnumerable supports deferred execution.
- IEnumerable supports further filtering.
IEnumerable VS IEnumerator
Both of interfaces help to loop through the collection.
in the case of IEnumerator, we need to invoke the MoveNext method and to retrieve the current item, we need to invoke the current property.
Relation
The IEnumerable interface actually uses IEnumerator. The main reason to create an IEnumerable is to make the syntax shorter and simpler.
If you go to the definition of the IEnumerable<T> interface, you will see this interface has a method GetEnumerator() that returns an IEnumerator object back.
In short, this IEnumerable uses IEnumerator internally.
Differences
The main difference between IEnumerable and IEnumerator is an IEnumerator retains its cursor's current state.
IList and List
IList is an interface and List is concrete class.
Let's suppose you have a business object where you want to use a object of type Apple. May be it is fine for now but later you may need to support Mango type object. In that case you may probably need to change the business layer.
To get rid of these tight coupling you need to use interface like IFruit. Then your business layer will not depend just on Apple class and you will get rid of tight coupling.
Let's suppose you have a business object where you want to use a object of type Apple. May be it is fine for now but later you may need to support Mango type object. In that case you may probably need to change the business layer.
To get rid of these tight coupling you need to use interface like IFruit. Then your business layer will not depend just on Apple class and you will get rid of tight coupling.
Reference: https://www.c-sharpcorner.com
0 comments:
Post a Comment