Wednesday, January 29, 2014

Sorting a List in C#

I often receive emails from developers asking for help with their development conundrums. One of the common questions I get asked, especially from someone learning C# and writing their first app, is how to sort a list of items.

It's quite simple actually; there are 2 ways you can sort a list, and both have their own purpose as defined below.

Using the first method you can sort a list in place, i.e. without having to create a copy of the list. E.g. if you had a list of an object which contained a date and you would like to sort the list in chronological order, you can do something like the following:

MyList.Sort((x, y) => x.OrderDate.CompareTo(y.OrderDate));

The second method does not sort the list in place, but rather returns a sorted copy of the original list:

List<Employees> lstEmployees = MyList.OrderBy(emp => emp.JoinDate).ThenBy(emp => emp.empID).ToList();

This example also shows you how to sort the list based on 2 parameters, in this case Employee Join Date and Employee ID, so if there were multiple employees who joined the company on the same date, they will be further sorted by their Employee ID.

Hope this helps!

Paras Wadehra
Nokia Developer Ambassador
INETA Community Champion
Twitter: @ParasWadehra