Mental Jetsam

By Peter Finch

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.

Advertisements

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

 
%d bloggers like this: