Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 278
Elander Avatar asked Feb 16 '23 09:02

Elander


2 Answers

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

like image 151
Kamil Budziewski Avatar answered Feb 17 '23 21:02

Kamil Budziewski


You can assign the result of applying the first sort-order (i.e. OrderBy) to a variable of type IOrderedEnumerable and then call ThenBy in a loop assigning to the same variable as many times as required.

like image 36
David Avatar answered Feb 17 '23 22:02

David