Wednesday, August 27, 2008

Sorting a List using delegates

I have to sort Lists of Custom classes relatively frequently. Everytime I am about to write the Sort code, I always forget how to do it for a breif second. So as a reminder, I thought I would put a post on how to do it.

Say you have a List of Customer classes.

List customerList = new List();
customerList.PopulateList();

Now if you want to sort by a property in the list (for example BusinessName) you can do the following:

customerList.Sort( delegate( Customer x, Customer y)
{
return x.BusinessName.CompareTo(y.BusinessName);
}

Done.

7 comments:

Shaun Austin said...

Hmmm I'd probably want to use the culture specific version is the culture specific version of CompareTo and pass in CultureInfo.CurrentUICulture to ensure localized sorting behaviour at the very least. (FXCop would chew you a new one!!!)

Shaun Austin said...

stoopid iPhone keyboard!!!!!!

Shaun Austin said...

Note to self: stop treating all blog posts like stack overflow questions. There is no rep gained by commenting here!!!!!

Anonymous said...

[B]NZBsRus.com[/B]
Dont Bother With Idle Downloads With NZB Files You Can Easily Search Movies, Games, MP3 Singles, Software and Download Them @ Flying Rates

[URL=http://www.nzbsrus.com][B]Newsgroup[/B][/URL]

Anonymous said...

[B]NZBsRus.com[/B]
Escape Sluggish Downloads With NZB Files You Can Quickly Find Movies, PC Games, MP3 Singles, Software & Download Them at Fast Rates

[URL=http://www.nzbsrus.com][B]Usenet Search[/B][/URL]

Anonymous said...

Infatuation casinos? vouch for this untested [url=http://www.realcazinoz.com]casino[/url] seemly and hold a combat up online casino games like slots, blackjack, roulette, baccarat and more at www.realcazinoz.com .
you can also horn in with our redesigned [url=http://freecasinogames2010.webs.com]casino[/url] leadership at http://freecasinogames2010.webs.com and pick up real away misled !
another latest [url=http://www.ttittancasino.com]casino spiele[/url] within an eyelash of is www.ttittancasino.com , during german gamblers, project manumitted online casino bonus.

Anonymous said...

Inquire about Our Cheerless Prices at www.Pharmashack.com, The Portentous [b][url=http://www.pharmashack.com]Online Chemist's workshop [/url][/b] To [url=http://www.pharmashack.com]Buy Viagra[/url] Online ! You Can also Drive to Countless Deals When You [url=http://www.pharmashack.com/en/item/cialis.html]Buy Cialis[/url] and When You You [url=http://www.pharmashack.com/en/item/levitra.html]Buy Levitra[/url] Online. We Also Carry off in a Matchless Generic [url=http://www.pharmashack.com/en/item/phentermine.html]Phentermine[/url] On account of Your Nutriment ! We Peddle Tick [url=http://www.pharmashack.com/en/item/viagra.html]Viagra[/url] and Also [url=http://www.pharmashack.com/en/item/generic_viagra.html]Generic Viagra[/url] !