C# list sort by two columns

前端 未结 7 1100
慢半拍i
慢半拍i 2020-12-15 21:08

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

相关标签:
7条回答
  • 2020-12-15 22:01

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

    0 讨论(0)
提交回复
热议问题