Sunday, 5 October 2008

Sorting Generic Collections

You can simplify the sorting by using the anonymous delegate as shown below and you don't need to implement IComparable interface:

(Note: For a simpler technique using LINQ see: Sorting Generic Collections - Redux)
List persons = new List();
persons.Add( new Person("Tom",30) );
persons.Add(new Person("Harry", 55));

// sort in ascending order
persons.Sort( delegate(Person person0, Person person1)
{
return
person0.FirstName.CompareTo(person1.FirstName);
} );


// sort in descending order
persons.Sort( delegate(Person person0, Person person1)
{
return
person1.FirstName.CompareTo(person0.FirstName);
} );

No comments: