Showing posts with label Ienumerator generic collections. Show all posts
Showing posts with label Ienumerator generic collections. Show all posts

Sunday, October 30, 2011

Iterating through collections without For and Foreach using IEnumerable and IEnumerator


We were using a number of collections holding same type of data. Someone asked me if there is a way to handle these collections in a common way. In other words how do we iterate through different kinds of collection using a common function .I told them we could achieve the same using  a function with IEnumerable<T>  . I demonstrated the same using 3 collections Generic Stack, Queue, and Ordered List.
Following is the code snippet that demonstrates the same

using System;
using System.Collections.Generic;
using System.Collections;

namespace testCollection
{
    class Program
    {
        static void Main(string[] args)
        {

            //Stack of integers
            Stack<int> stackCollection = new Stack<int>();
            stackCollection.Push(1);
            stackCollection.Push(2);
            stackCollection.Push(3);
            stackCollection.Push(4);
            stackCollection.Push(5);

            //Queue of Integers
            Queue<int> queueCollection = new Queue<int>();
            queueCollection.Enqueue(1);
            queueCollection.Enqueue(2);
            queueCollection.Enqueue(3);
            queueCollection.Enqueue(4);
            queueCollection.Enqueue(5);

            //ordered list of integers
            List<int> listCollection = new List<int>();
            listCollection.Add(1);
            listCollection.Add(2);
            listCollection.Add(3);
            listCollection.Add(4);
            listCollection.Add(5);

            //iterates through the stack of items in last in first out manner
            GetItems(stackCollection);

            //iterates through the queue in a fist in first out  manner
            GetItems(queueCollection);

            //Iterates through an ordered list of integers
            GetItems(listCollection);

            Console.ReadLine();


        }

        /// <summary>
        /// generic iteration logic for a collection
        /// </summary >
        /// <param name="collection"> is decided at runtime and instance of a class implementing ienumerable</param>
        public static void GetItems(IEnumerable<int> collection)
        {

            //gets the enumerator
            IEnumerator<int> enumerator = collection.GetEnumerator();
            while (enumerator.MoveNext ())
            {

                //gets the items from the collection
                Console.WriteLine(enumerator.Current);  
            }


        }
    }
}