Welcome to Devintelligence.com Sign in | Join | Help

.Net Adventures

In .Net we trust
Error!
HTTP/1.1 404 Not Found


Sorting System.Collections.Generic.List<T>

This post shows the sorting techinque using anonymous delegate that can be implemented in any custom type generic lis 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: , ,
Posted: Tuesday, January 16, 2007 1:50 PM by adventurer

Comments

Jason Haley said:

# January 16, 2007 9:00 PM

Jason Haley said:

# January 16, 2007 9:01 PM

DotNetKicks.com said:

You've been kicked (a good thing) - Trackback from DotNetKicks.com

# March 13, 2007 12:15 PM

.Net LIfe said:

Great example of sorting a Generic.List&lt;T&gt; collection of objects can be found here

# January 15, 2008 3:04 PM

.Net Life said:

Great example of sorting a Generic.List&lt;T&gt; collection of objects can be found here . For future

# January 16, 2008 11:39 AM

Wayne John said:

Sorting Generic.List Items

# April 21, 2008 11:28 AM

Wayne John said:

Sorting Generic.List Items

# May 9, 2008 10:16 AM
New Comments to this post are disabled