Popular Posts

There was an error in this gadget

Feb 2, 2011

Using List<> in C#



Both the List<T> and ArrayList classes have properties very similar to C# arrays. One key advantage of these classes over arrays is that they can grow and shrink as the number of stored objects changes.
The List<T> class is contained with the System.Collections.Generic namespace whilst the ArrayList class is contained within theSystem.Collections namespace.
The syntax for creating a List<T> collection is as follows:
List<typename = new List<type>();


Step1: Make a new project. Select console application. named the project ListNamed.
Step2: Make a class Person.cs
Type the code
public class Person
    {
        public int age;
        public string name;

        public Person(int age, string name)
        {

            this.age = age;

            this.name = name;

        }

    }
Step3:In Program.cs file type the code like this…
List<Person> people = new List<Person>();

            people.Add(new Person(50, "Ahmed"));
            people.Add(new Person(30, "Saikat"));
            people.Add(new Person(26, "Rumon"));
            people.Add(new Person(24, "Jubayer"));
            people.Add(new Person(25, "Khalid"));
            people.Add(new Person(6, "Ismail"));


            Console.WriteLine("Unsorted list");

            people.ForEach(delegate(Person p)
            { Console.WriteLine(String.Format("{0} {1}", p.age, p.name)); });

            // Find the young
            List<Person> young = people.FindAll(delegate(Person p) { return p.age < 25; });
            Console.WriteLine("Age is less than 25");

            young.ForEach(delegate(Person p)
            { Console.WriteLine(String.Format("{0} {1}", p.age, p.name)); });

            // Sort by name
            Console.WriteLine("Sorted list, by name");
            people.Sort(delegate(Person p1, Person p2)
            { return p1.name.CompareTo(p2.name); });

            people.ForEach(delegate(Person p)
            { Console.WriteLine(String.Format("{0} {1}", p.age, p.name)); });

            // Sort by age
            Console.WriteLine("Sorted list, by age");

            people.Sort(delegate(Person p1, Person p2)
            { return p1.age.CompareTo(p2.age); });

            people.ForEach(delegate(Person p)
            { Console.WriteLine(String.Format("{0} {1}", p.age, p.name)); });

            Console.ReadLine();

Step4:Run the project. You will see the result…


No comments:

Post a Comment