Thursday, August 28, 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 brief 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. 

```csharp
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:

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

Done.

6 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.