Tuesday, June 18, 2013

Save and process class object using List

Here I am going to discuss how to store a set of object in lsit and how to manipulate the list using foreach loop. Now, it may seem very basic for you but please think that day when you had just learned how to use list or collection in .NET and that day probably you had no idea to store class object with collection. Sorry to bring you few years back. Let’s see how it works. Again my silly Person class is in picture. I have created List

            IList<Person> list = new List<Person>();

to store object of Person class.  And foreach loop is used to iterate through collection.

    class Person
    {
        public string Name { get; set; }
        public string Surname { get; set; }
    }

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

            foreach (var v in list)
            {
                Console.Write("Name:-" + v.Name + " Surname:- " + v.Surname +"\n");
            }
            Console.ReadLine();          
        }
    }


No comments:

Post a Comment