Wednesday, 18 February 2015

Enumerators in C# (IEnumerable And IEnumerator )

Enumerators are used to read data in the collection

IEnumerator

IEnumerator it allows us to iterate over list, array, etc and process each element one-by-one.

Basic Example:

namespace Enumerators
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> names = new List<string>() { "A", "B", "C","D","E" };
            foreach (string a in names)
            {
                Console.WriteLine(a);
            }
            Console.ReadKey();
        }
    }

}

Output:




Now, if we are using IEnumerator ,



It has  two abstract methods and a property 

void Reset() : Sets  to initial position.(which is before the first element in the collection (-1)
bool MoveNext() : It moves to Next Element.
object Current : current element.

Basic Example:

namespace Enumerators
{
    class Program
    {
        static void Main(string[] args)
        {
            string name = "Uday";
            IEnumerator enumerator = name.GetEnumerator();
            while (enumerator.MoveNext())
            {
                char curObject = (char)enumerator.Current;
                Console.Write(curObject + ".");
            }
            Console.Read();
        }
    }
}


Output:


Example 2:

namespace Enumerators
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> names = new List<string>() { "A", "B", "C","D","E" };
            IEnumerator<string> ab = names.GetEnumerator();
            ab.MoveNext();
            Console.WriteLine(ab.Current);
            ab.MoveNext();
            Console.WriteLine(ab.Current);
            ab.Reset();
            Console.ReadKey();
        }
    }
}

Output:








namespace Enumerators
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> names = new List<string>() { "A", "B", "C","D","E" };
            IEnumerator a = names.GetEnumerator();
            while (a.MoveNext()) 
            Console.WriteLine(a.Current); 
            Console.ReadKey();
        }
    }
}

output:



Note:

Here we are using,while rather than foreach because foreach cannot be used with IEnumerator

IEnumerator use While, MoveNext, current to get current record
IEnumerator cannot be used in foreach loop
IEnumerator allows readonly access to a collection

We will get error if, we are using foreach.




IEnumerable:

The IEnumerable interface is a generic interface for looping over elements.
It has foreach support.

The IEnumerable interface contains an abstract member function called GetEnumerator() and return an interface IEnumerator on any success call. 


Note: IEnumerator interface is meant to be used as accessors, it wil not be useful  to make any changes in the collection or elements of the collection.

 Advantages:

IEnumerable code are clear and can be used in foreach loop
IEnumerable doesn’t remember state
IEnumerable defines one method GetEnumerator which returns an IEnumerator

Example:
namespace Enumerators
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> names = new List<string>() { "A", "B", "C","D","E" };
            IEnumerable a = (IEnumerable)names;
            foreach (string name in a)
            {
                Console.WriteLine(name);
            }
            Console.ReadKey();
        }
    }

}
Output:




Building Your Own C# Enumerator To Use With The foreach 


Example:


class Students
{
    private int Id;
    private string Name;
    private string City;
    private int Department;
    public Students(int id, string name, string city, int department)
    {
        this.Id = id;
        this.Name = name;
        this.City = city;
        this.Department = department;
    }
    public int ID
    {
        get
        {
            return this.Id;
        }
    }
    public override string ToString()
    {
        return "Id:" + this.Id.ToString() + "\nName:" + Name + "\nCity :" + City + "\nDepartment:" + Department.ToString();
    }
}

class StudentsDetails : IEnumerableIEnumerator
{
    ArrayList StudentsArray = new ArrayList();
    private int Position = -1;
    public void AddEmployee(Students student)
    {
        StudentsArray.Add(student);
    }
// Implementation of IEnumerable
    public IEnumerator GetEnumerator()
    {
        return (IEnumerator)this;
    }
   
// Implementation of IEnumerator

public bool MoveNext()
    {
        if (Position < StudentsArray.Count - 1)
        {
            ++Position;
            return true;
        }
        return false;
    }
    public void Reset()
    {
        Position = -1;
    }
    public object Current
    {
        get
        {
            return StudentsArray[Position];
        }

    }

public static void Main()
    {
        StudentsDetails studentDetails = new StudentsDetails();
        Students student1 = new Students(1,"A","HYDERABAD",9);
        Students student2 = new Students(2,"B", "HITECHCITY", 9);
        studentDetails.AddEmployee(student1);
        studentDetails.AddEmployee(student2);
        Console.WriteLine("Using foreach");
        foreach (Students emp in studentDetails)
        {
            Console.WriteLine(emp);
        }
        Console.WriteLine("\n Here GetEnumerator returns IEnumerator");
        IEnumerator StudentEnumerator = studentDetails.GetEnumerator();
        StudentEnumerator.Reset();
        while (StudentEnumerator.MoveNext())
        {
            Console.WriteLine((Students)StudentEnumerator.Current);
        }
        Console.ReadKey();

    }







Output:





Example:

class Students
{
    public static void Main()
    {
        List<string> names = new List<string>();
        names.Add("A");
        names.Add("B");
        names.Add("C");
        names.Add("D");
        names.Add("E");
        names.Add("F");
        names.Add("G");
        Console.WriteLine("list to IEnumerable");
        IEnumerable<string> names_Enumerator = (IEnumerable<string>)names;
        foreach (string a in names_Enumerator)
            Console.WriteLine(a);
        Console.ReadKey();
    }
}



Output:





Example:

class Students
{
    public static void Main()
    {
        List<string> names = new List<string>();
        names.Add("A");
        names.Add("B");
        names.Add("C");
        names.Add("D");
        names.Add("E");
        names.Add("F");
        names.Add("G");
        Console.WriteLine("list to IEnumerator");
        IEnumerator<string> names_IEnumerator = names.GetEnumerator();
        while (names_IEnumerator.MoveNext())
            Console.WriteLine(names_IEnumerator.Current); 
        Console.ReadKey();
    }

}


Output:





IEnumerable does not  remember  state, which row or record it is iterating while IEnumerator remembers the state


Example with IEnumerator ( Remembers State)


class Students
{
    public void PrintMarksUptO35(IEnumerator<int> marksa)
    {
        while (marksa.MoveNext())
        {
            Console.WriteLine(marksa.Current);
            if (marksa.Current > 60)
            {
                PrintMarksGreater60(marksa);

            }
        }
    }

    public void PrintMarksGreater60(IEnumerator<int> marks)
    {
        while (marks.MoveNext())
        {
        Console.WriteLine(marks.Current);
        Console.WriteLine("Distinction");
        }
    }
    
    static void Main()
    {
        List<int> marks = new List<int>();
        marks.Add(20);
        marks.Add(30);
        marks.Add(40);
        marks.Add(50);
        marks.Add(60);
        marks.Add(70);
        marks.Add(80);
        marks.Add(90);
        IEnumerator<int> marksa = marks.GetEnumerator(); 
        Students obj = new Students();
        obj.PrintMarksUptO35(marksa);
        Console.ReadKey();
    }
}


Output:


IEnumerable doesn’t remember state

Example:

class Students
{
    public void PrintMarksUptO35(IEnumerable<int> marksa)
    {
        foreach (int a in marksa)
        {
            Console.WriteLine(a);
            if (a > 35)
            {
                Console.WriteLine("Passed");
                PrintMarksGreater35(marksa);
            }
        }
    }

    public void PrintMarksGreater35(IEnumerable<int> marks)
    {
        foreach (int a in marks)
            Console.WriteLine(a);
    }
    
    static void Main()
    {
        List<int> marks = new List<int>();
        marks.Add(20);
        marks.Add(30);
        marks.Add(40);
        marks.Add(50);
        marks.Add(60);
        marks.Add(70);
        marks.Add(80);
        marks.Add(90);
        IEnumerable<int> a = (IEnumerable<int>)marks;
        Students obj = new Students();
        obj.PrintMarksUptO35(a);
        Console.ReadKey();
    }
}


Output:



No comments:

Post a Comment