Tuesday, 6 March 2012

How to iterate through custom types?


Yes, till now we seen iterate through premitive type like int,float,double,….ect we have many way we can iterate like for,foreach,Interface based(IEnumerable,IEnumerable<T)), but now we want iterate through custom objects like employee,student,customer…ect.
In Custom types also we can enumerate through the objects in same like premitive types
Ex: Create one Custom type is Student
    class Student
    {     
            public Student()
            {
                                                 // Default Constructor
            }
            public Student(int sno, string sname)
            {
                this._stno = sno;
                this.stname = sname;   // Paramerized constructor
            }
            int _stno;
            public int Stno
            {
                get { return _stno; }
                set { _stno = value; }
            }
            private string stname;
            public string Stname
            {
                get { return stname; }
                set { stname = value; }

            }         
            static void Main()
            {
                Student stu = new Student(101, "naga");
                Student stu1 = new Student(102, "kasi");
                List<Student> obj = new List<Student>();
                obj.Add(stu);
                obj.Add(stu1);
                foreach (Student item in obj)
                {
                    Console.Write(item.Stno +"\n");
                    Console.Write(item.Stname + "\n");
                }
                Console.WriteLine();
                Console.WriteLine("-----2nd way---------"); 

Student[] objs = new Student[] { new Student(1, "anand"), new Student(2,"rohit")};

                // Or
                Student[] objs = new Student[2];
                objs[0]=new Student(104,"babuu");
                objs[1] = new Student(107, "chanti");
                 // Or
                 List<Student>  objs = new List<Student>();
                
objs.Add(new Student(11, "kasi"));
                
objs.Add(new Student(12, "babu"));        

                List<Student> stulists = new List<Student>(objs);
               
                foreach (Student item in stulists)
                {
                    Console.Write(item.Stno + "\n");
                    Console.Write(item.Stname + "\n");
                }
                Console.WriteLine("........3rd way.............");

                IEnumerator<Student> objstu = obj.GetEnumerator();
                while (objstu.MoveNext())
                {
                    Student ss = objstu.Current;
                    Console.WriteLine(ss.Stno);
                    Console.WriteLine(ss.Stname);
                }               
                Console.Read();
            }
        }

No comments:

Post a Comment