Mental Jetsam

By Peter Finch

  •  

    January 2009
    M T W T F S S
    « Nov   Feb »
     1234
    567891011
    12131415161718
    19202122232425
    262728293031  
  • My del.icio.us links

  • Flickr Photos

    S5001187

    S5001169

    S5001136

    More Photos
  • Wordpress Stuff

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 »