Sorting System.Collections.Generic.List<T>

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

class Person:IComparable 
{ 
    private string _FirstName; 
    private int _Age; 
 
    public Person(string _FirstName, int _Age) 
    { 
        this._FirstName = _FirstName; 
        this._Age = _Age; 
    } 
    public string FirstName 
    { 
        get  
        { 
            return _FirstName; 
        } 
        set  
        { 
            _FirstName = value; 
        } 
    } 
    public int Age 
    { 
        get  
        { 
            return _Age; 
        } 
        set  
        { 
            _Age = value; 
        } 
    } 
    // sorting in ascending order  
    public int CompareTo(object obj) 
    { 
        Person person = (Person) obj; 
        return this.FirstName.CompareTo(person); 
    } 
}
 

But you can simplify the sorting just by using the anonymous delegate as shown bellow and you don’t need to implement IComparable interface

List<Person> persons = new List<Person>(); 
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); 
} 
);
 

Technorati tags: generic, c#, code

Leave a Reply