This post shows the sorting technique using anonymous delegate that can be implemented in any custom type generic list based on the selected property.For sorting any custom type the class must implement the System.IComparable interface. Now let me assume you have a Person class and if you want to sort the list of person objects then you must implement System.IComparable interface and write the logic of how our person object is to be sorted in the CompareTo method
using System;
namespace ConsoleApplication1
{
class Person : IComparable
{
public Person(string firstName, int age)
{
FirstName = firstName;
Age = age;
}
public string FirstName
{
get;
set;
}
public int Age
{
get;
set;
}
// sorting in ascending order
#region IComparable Members
public int CompareTo(object obj)
{
var person = (Person) obj;
return FirstName.CompareTo(person);
}
#endregion
}
}
But you can simplify the sorting just by using the anonymous delegate as shown bellow and you don’t need to implement IComparable interface
var persons = new List<Person>
{
new Person("Tom", 30),
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);
});
Technorati tags: generic, c#, code