Search code examples
c#sortingsql-order-bycriteria

'Then By' usage with different number of criterias


I am writing a C# program that allows user to specify sorting criterias. For example, the user can sort only by "serviceName", or add several other criterias like "isHD" or "isGood". What I ask is, I want to use '.Then By' statement but the user determines how many times I need to write it.

Is there any way that I can get some flexibility on the number of criteria depending on a switch/case block? e.g

List.OrderBy(t => t.name)
List.OrderBy(t => t.isHD).ThenBy(t => t.name)
List.OrderBy(t => t.isGood).ThenBy(t => t.name).ThenBy(t => t.isHD)

Also the order of these criteria will be chosen by the user.


Solution

  • you can use generic method:

        public List<T> SortBy<T>(List<T> list, params Func<T, object>[] selectors)
        {
            var ordered = list.OrderBy(selectors[0]);
            for (int i = 1; i < selectors.Count(); i++)
            {
                ordered= ordered.ThenBy(selectors[i]);
            }
            return ordered.ToList();
        }
    

    run it:

    SortBy(List, x=>x.name, x=>x.isHD, x=>x.isGood)
    

    which will do:

    List.OrderBy(x=>x.name).ThenBy(x=>x.isHD).ThenBy(x=>x.isGood)
    

    can be improved by checking if selectors where passed