How to use IEnumerable/IEnumerator

Hmanjarawala
Posted by in C# category on for Intermediate level | Points: 250 | Views : 12367 red flag
Rating: 4.5 out of 5  
 4 vote(s)

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 one

Objective

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<string> Oceans = new List<string>();

Oceans.Add("Pacific");
Oceans.Add("Atlantic");
Oceans.Add("Indian");
Oceans.Add("Southern");
Oceans.Add("Arctic");

Now, 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)
{     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.

Page copy protected against web site content infringement by Copyscape

About the Author

Hmanjarawala
Full Name: Himanshu Manjarawala
Member Level: Bronze
Member Status: Member
Member Since: 7/30/2011 7:42:18 AM
Country: India
Himanshu Manjarawala Sr. Software Engineer@AutomationAnywhere http://fieredotnet.wordpress.com/
http://himanshumbri.blogspot.com
I am Himanshu Manjarawala, Graduate in Computer Science and MCA From Veer Narmad South Gujarat University, Surat Gujarat India. Currently working as Sr. Software Developer in Automation Anywhere.

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)