Mental Jetsam

By Peter Finch

Archive for January, 2009

Sorting an array in C#

Posted by pcfinch on January 14, 2009

The following code is a simple and quick way to sort and arbitrary array of objects in C#. I like using a delegate in this way as you can pick any attribute or member of the object to sort on at the time you need to perform the sort in the code.

class Customer {
	internal String sName ;
	internal String sAddress ;
} ;

Customer[] customers = new Customer[20] ;
/* Load array ...*/

Array.Sort<Customer>(customers, new Comparison<Customer>(delegate(Customer l, Customer r)
	return (l.sName.CompareTo(r.sName));
})) ;

Make sure the array is full, i.e. no null entries, otherwise you will have to check for null values in l and r.

Posted in C#.NET | Leave a Comment »