I have a C# custom object list that I need to sort by two different variables one is a boolean and the other is a string. I can sort by either of the criteria, but
Here is an extension method I wrote for sorting a list by any number of keys:
public static class ListExtensions
{
public static void SortBy<T>(this List<T> list, params Expression<Func<T, IComparable>>[] keys)
{
if (list == null)
throw new ArgumentNullException("list");
if(keys == null || !keys.Any())
throw new ArgumentException("Must have at least one key!");
list.Sort((x, y) => (from selector in keys
let xVal = selector.Compile()(x)
let yVal = selector.Compile()(y)
select xVal.CompareTo(yVal))
.FirstOrDefault(compared => compared != 0));
}
}
Usage:
var List<Person> persons = GetPersons();
myList.SortBy(p => p.LastName, p => p.FirstName);
Note that this is roughly equivalent to: myList = myList.OrderBy(p => p.LastName).ThenBy(p => p.FirstName)
.