Translate

Saturday, November 26, 2011

ienumerable tutorial c#


Definitions of IEnumerator and IEnumerable 

If a class implements Ienumerable, then you can run a foreach loop on an instance of that class.

In the .net framework

IEnumerator is defined as 


namespace System.Collections
{   

    public interface IEnumerator
    {        
        object Current { get; }
        bool MoveNext();
        void Reset();
    }
}


IEnumerable is defined as 

namespace System.Collections
{

    public interface IEnumerable
    {        
        IEnumerator GetEnumerator();
    }
}


If you are familiar with SQL, think of IEnumerator as a cursor and IEnumerable as a table.


 Implementation of  IEnumerator and IEnumerable 

using System;
using System.Text;
using System.Collections;
 
namespace ConsoleApplication4
{
 
    class Program
    {
        static void Main(string[] args)
        {
            BookEnumerable books = new BookEnumerable();
            foreach (Book b in books)
            {
                Console.WriteLine(b.title);
            }
 
 
        }
    }
 
    public class Book
    {
        public string title;
        public int cost;
    }
 
    class BookEnumerable : IEnumerable
    {
        IEnumerator er = new BookEnumerator();
 
        public IEnumerator GetEnumerator()
        {
            return er;
        }
    }
 
 
    class BookEnumerator : IEnumerator
    {
 
 
        Book[] books = Utilities.GetBookArray();
 
 
 
        int position = -1;
 
        public object Current
        {
            get
            {
                return books[position];
            }
        }
 
        public bool MoveNext()
        {
 
            position++;
            if (position < books.Length)
            {
                return true;//this means a next item exists
            }
            else
            {
                return false;//this means there are no more items to move further to
            }
        }
 
        public void Reset()
        {
            position = -1;
        }
 
 
    }
 
    public class Utilities
    {
        public static Book[] GetBookArray()
        {
            Book b1 = new Book();
            b1.title = "Code Complete";
            b1.cost = 28;
 
            Book b2 = new Book();
            b2.title = "The Pragmatic Programmer";
            b2.cost = 33;
 
            return new Book[] { b1, b2 };
 
        }
    }
}

No comments:

Post a Comment

Comments will appear once they have been approved by the moderator