This article describes use of IEnumerable interface for Collection types.
Introduction
IEnumerable is an interface, implemented by
System.Collecetion
type in .Net that provides iterator pattern. The definition according to MSDN is:
“Exposes 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 oneObjective
Explore usage of IEnumerable and IEnumerator for user defined class.
Description
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 Oceans = new List();
Oceans.Add("Pacific");Oceans.Add("Atlantic");Oceans.Add("Indian");Oceans.Add("Southern");Oceans.Add("Arctic");
// rather than a typical index number if we used a for loop.
List
Now, we already knows how to iterate each element using foreach loop
// HERE is where the Enumerator is gotten from the Listobject foreach(string ocean in Oceans) { Console.WriteLine(ocean); }
// We can do same thing using IEnumerable/IEnumerator. IEnumerator enumerator = Oceans.GetEnumerator();
while(enumerator.MoveNext()) { string ocean = Convert.ToString(enumerator.Current); Console.WriteLine(ocean); }
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.