Tuesday, April 28, 2009

How to sort list of objects in C#

The following code helps in sorting list of objects based on some property’s value.

public class Person
{
public int age;
public string name;

public Person(int age, string name)
{
this.age = age;
this.name = name;
}
}

List people = new List();

people.Add(new Person(50, “Kiran”));
people.Add(new Person(30, “Raghava”));
people.Add(new Person(26, “Andrew”));
people.Add(new Person(24, “Praveen”));
people.Add(new Person(5, “Sudhir”));
people.Add(new Person(6, “Prudhvi”));

Console.WriteLine(”Unsorted list”);
people.ForEach(delegate(Person p) { Console.WriteLine(String.Format(”{0} {1}”, p.age, p.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)); });

people.Sort(delegate(Person p1, Person p2) { return p1.age.CompareTo(p2.age); });
Console.WriteLine(”Sorted list, by age”);
people.ForEach(delegate(Person p) { Console.WriteLine(String.Format(”{0} {1}”, p.age, p.name)); });

7 comments:

RRave said...

Dear Sir,

I have a launched new web site for .NET programming resources. www.codegain.com. I would like to invite to the codegain.com as author and supporter. I hope you will joins with us soon.

Thank You
RRaveen
Founder www.codegain.com

Kiran said...

Excellent. You can also do this sorting with LINQ in C#3.0

Kiran said...

Works great!!! Thx!!!

Kiran said...

very good

Kiran said...

XClnt

Kiran said...

thank you!

Kiran said...

Super thanks a lot