DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Building Scalable Real-Time Apps with AstraDB and Vaadin
Register Now

Trending

  • What Is Envoy Proxy?
  • Java String Templates Today
  • Scaling Site Reliability Engineering (SRE) Teams the Right Way
  • What Is Istio Service Mesh?

Trending

  • What Is Envoy Proxy?
  • Java String Templates Today
  • Scaling Site Reliability Engineering (SRE) Teams the Right Way
  • What Is Istio Service Mesh?
  1. DZone
  2. Data Engineering
  3. Data
  4. IEnumerable vs. IEnumerator

IEnumerable vs. IEnumerator

It all depends on your iteration variable.

neeraj kumar user avatar by
neeraj kumar
·
Aug. 13, 19 · Tutorial
Like (2)
Save
Tweet
Share
15.29K Views

Join the DZone community and get the full member experience.

Join For Free

In this blog, I will try to explain the difference between IEnumerable and IEnumrator by using a simple example. First, we will understand the meaning of both of the terms and why we are using them.

What are IEnumerable and IEnumerator?

namespace System.Collections.Generic
{
    //
    // Summary:
    //     Exposes the enumerator, which supports a simple iteration over a collection of
    //     a specified type.
    //
    // Type parameters:
    //   T:
    //     The type of objects to enumerate.
    public interface IEnumerable<out T> : IEnumerable
    {
        //
        // Summary:
        //     Returns an enumerator that iterates through the collection.
        //
        // Returns:
        //     An enumerator that can be used to iterate through the collection.
        IEnumerator<T> GetEnumerator();
    }
}


The above code explains that IEnumerable internally implements the GetEnumerator() function of IEnumerator. From this, we can say IEnumerable works in the same way as IEnumerator, but there is a big difference between them that we will see with the help of example given below.

Both IEnumerable and IEnumrator are used to iterate through a collection object.

Let's look at this example:

static void Main(string[] args)
        {
            List<int> IDS = new List<int>();
            IDS.Add(1);
            IDS.Add(2);
            IDS.Add(3);
            IDS.Add(4);
            IDS.Add(5);

            IEnumerable<int> enumerableList = (IEnumerable<int>)IDS;

            foreach (var id in enumerableList)
            {
                Console.WriteLine("id in enumerableList is {0}", id);
            }
            IEnumerator<int> enumeratorList = IDS.GetEnumerator();

            while (enumeratorList.MoveNext())
            {
                Console.WriteLine("id in enumeratorList is {0}", enumeratorList.Current);
            }

            Console.ReadKey();
        }


In the code block above, we created a List IDS of type integer and added some values to the list. Now, we create an object of IEnumerable<int> as enumerableList and initialize it with list IDS. We follow the same process for the IEnumerator. After creating the objects, we iterate through them. As we can see in the example, IEnumerator has some extra methods to perform operations, such as MoveNext() to find the next element and Current() to get the current value, as the same suggests.

Output for the cases will be the same; the only difference we can see here is we have written more code in IEnumerator for doing the same amount of work.

As we have seen IEnumerable internally implements IEnumerator, so using IEnumerable means we can write less code for the same work of iterating through a list.

Here's the question, "Why are we even using IEnumerator for iterating through any collection?"

Well, IEnumerator maintains the state for an iterating variable.

What does that mean, and what's its use? Modify the above example as:

 class Program
    {
        static void Main(string[] args)
        {
            List<int> IDS = new List<int>();
            IDS.Add(1);
            IDS.Add(2);
            IDS.Add(3);
            IDS.Add(4);
            IDS.Add(5);

            IEnumerable<int> enumerableList = (IEnumerable<int>)IDS;

            foreach (var id in enumerableList)
            {
                Console.WriteLine("id in enumerableList is {0}", id);
                if (id > 3)
                {
                    StateEnumerable(enumerableList);
                    break;
                }

            }
            IEnumerator<int> enumeratorList = IDS.GetEnumerator();

            while (enumeratorList.MoveNext())
            {
                Console.WriteLine("id in enumeratorList is {0}", enumeratorList.Current);
                if (enumeratorList.Current > 3)
                {
                   StateEnumerator(enumeratorList);
                    break;
                }

            }


            Console.ReadKey();
        }
        public static void StateEnumerable(IEnumerable<int> enumerableList)
        {
          foreach(int item in enumerableList)
            {
                Console.WriteLine("value from stateEnumerable function" + item);
            }
        }
        public static void StateEnumerator(IEnumerator<int> enumerator)
        {
            while (enumerator.MoveNext())
            {
                Console.WriteLine("value from stateEnumerator function" + enumerator.Current);
            }
        }
    }


Now, we have added two new methods in our class StateEnumerable(IEnumerable<int> enumerableList) and StateEnumerator(IEnumerator<int> enumerator). We call these methods in the loops of enumerableList and enumeratorList if the value of ID is greater than three.

Here, we are just interested in seeing how the iterating variable (looping variable as "var id in enumerable,id is iterating variable) state behaves in both the cases. Now, run this code and observe the outputs we get.

Output for the above code is :-
Output

So, here is the output, which explains the major difference between IEnumerator and IEnumerable. For a value of four for i, we called the method StateEnumerable function and StsteEnumerator

As IEnumerator is maintaining the state even after passing it, our other function started iterating from five, unlike IEnumerable, which started again from one.

Conclusion:

So it depends on our condition. If we want to iterate through the list (or any collection) at one time, then IEnumerable is the best choice, but if we want to preserve the state of an iteration variable, then we should go with IEnumerator.

Object (computer science) Blocks Blog Data Types Element

Opinions expressed by DZone contributors are their own.

Trending

  • What Is Envoy Proxy?
  • Java String Templates Today
  • Scaling Site Reliability Engineering (SRE) Teams the Right Way
  • What Is Istio Service Mesh?

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: