This article describes use of IEnumerable interface for Collection types.
IEnumerable is an interface, implemented by
System.Collecetion type in .Net that provides iterator pattern. The definition according
to MSDN is:
the enumerator, which supports simple iteration over non-generic collection.”
It’s something that you can loop over. That might be a List
or Array or anything else that supports foreach loop.
IEnumerator allows you to iterate over List or
array, and processes each element one by one
Explore usage of IEnumerable and IEnumerator for user
Let’s first show how both IEnumerable and IEnumerator works:
Let’s define List of string and iterate each element using iterator pattern
This is a collection that eventually we will use an Enumertor to loop through
// rather than a typical index number if we used a for loop.
List<string> Oceans = new List<string>();
we already knows how to iterate each element using foreach loop
// HERE is where the Enumerator is gotten from the List<string> object
foreach(string ocean in Oceans)
// We can do same thing using IEnumerable/IEnumerator.
IEnumerator enumerator = Oceans.GetEnumerator();
string ocean = Convert.ToString(enumerator.Current);
So that's the first advantage there: if your methods accept an IEnumerable rather than an array or list they become more powerful because you can pass more different kinds of objects to them.
Second and most important advantage over List and Array is, unlike List and Array, iterator block hold a single item in memory, so if you are reading the result from large SQL query you can limit your memory use to single record. Moreover this evaluation is lazy. so if you're doing complicated work to evaluate the enumerable as your read from it, that work doesn't happen until it's asked for.