Tuesday, June 18, 2013

Iterator design pattern in c#

Friend how are you. I am fine and enjoying my programmer life very much. Today let’s learn iterator design pattern with example. Iterator design pattern is very important design pattern where we can go through a collection of object.
Let me discuss when this particular design pattern comes in to play. Let take a collection of object (you may create collection of object in many ways like using list/Array/Hash Table etc) are there and according to user choice you want to pick particular object and want to work with this object.

You may thinking how it will work ? right ? –Let me discuss . Here I have created a collection of object of my Person class and set this object in class property. And my class is containing a index using which I am invoking particular object and returning that object to my client code(Here Main() function).

So as the name suggest ,we can iterate throughout collection of object and by sequentially or randomly we can access that. Let’s have a look to below code.  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Data;
using System.Diagnostics;
using System.Data.SqlClient;

namespace BlogProject
{
    public class Person
    {
        Int32 Index = 0;
        public string Name { get; set; }
        public String Surname { get; set; }
        public static List<Person> PersonCollection { get; set; }

        public void ShowAll()
        {
            foreach (var v in PersonCollection)
            {
                Console.WriteLine("Name:- "+ v.Name + "Surname:- "+ v.Surname);
            }
        }

        public Person GetPerson(int i)
        {
            List<Person> lst = Person.PersonCollection;
            if(i > lst.Count)
                return null;
            else
                return lst[i];
        }
    }

    class Program
    {
        static void Main(string[] args)
         {
             List<Person> list = new List<Person>();
             Person p = new Person();
             p.Name = "Sourav";
             p.Surname = "Kayal";
             list.Add(p);

             p = new Person();
             p.Name = "Ram";
             p.Surname = "Kayal";
             list.Add(p);
             Person.PersonCollection = list;

             Console.WriteLine("Enter object number to Access");
             Int32 Input = (Convert.ToInt32(Console.ReadLine()));
             p = p.GetPerson(Convert.ToInt32(Input));
             Console.WriteLine(p.Name + p.Surname);

             Console.ReadLine();          
        }
    }

}



No comments:

Post a Comment