Sort a enumerable list

Shows how to sort a enumerable list by using a delegate.

// Create a simple example list
List<string> TestList = new List<string>();
 
TestList.Add("Venezuela");
TestList.Add("Norway");
TestList.Add("Finland");
TestList.Add("Brazil");
TestList.Add("Germany");
TestList.Add("Australia");
TestList.Add("Fakeland");
 
 
// Sort the list by A-Z
TestList.Sort(delegate(string A, string B) { 
    return A.CompareTo(B);
});
 
// Print out the test list
foreach (string Country in TestList)
    Console.WriteLine(Country);
 
/*
Results:
 
Australia
Brazil
Finland
Germany
Norway
Venezuela
*/
Snippet Details




Sorry folks, comments have been deactivated for now due to the large amount of spam.

Please try to post your questions or problems on a related programming board, a suitable mailing list, a programming chat-room,
or use a QA website like stackoverflow because I'm usually too busy to answer any mails related
to my code snippets. Therefore please just mail me if you found a serious bug... Thank you!


Older comments:

Alucard June 10, 2009 at 07:54
:D
Where is the Fakeland in the Results
Tim Hustler June 02, 2008 at 15:29
Man this is a fine post. Sorting was the only thing i was missing.

I think i had it previously but only on a List<> with simple types like strings or ints

I'm using List<> with custom object a lot more these days, especially when using LINQ so this sorting delegate syntax get's a little tricky to follow

thanks for posting it man :¬)