A Tech Log

October 6, 2008

Sorting System.Collections.Generic.List

Filed under: Development — adallow @ 11:27 am
Tags:

To get the correct sorting on the .Sort method of the the Generic List, then objects that have been added to the list (e.g. of type <T>) should have implemented the IComparable interface and shold have implemented the CompareTo Method, such as:

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); } } However you can skip the need to implement the interface and CompareTo if you use a delegate on the call to the .Sort method as follows:
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); } ); From: http://devintelligence.com/blogs/netadventures/archive/2007/01/16/sorting-system-collections-generic-list-t.aspx
Advertisements

1 Comment »

  1. […] This is an old but a goodie from Albert over on his blog. It uses delegates to allow inline sorting of Generic collections based on the specific types without having implemented IComparable in the type being sorted. […]

    Pingback by jbablog.com | Sorting Collections without implementing IComparable — November 27, 2008 @ 6:00 pm | Reply


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: