Using "Then By" with a different number of criteria

I am writing a C # program that allows the user to set sorting criteria. For example, a user can only sort by "serviceName" or add several other criteria, such as "isHD" or "isGood". I ask, I want to use the .Then By operator, but the user determines how many times I need to write it.

Is there a way that I can get some flexibility regarding the number of criteria depending on the switch / case block? eg

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 selected by the user.

+4
source share
2 answers

you can use the general 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 the selector where passed

+6
source

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 the loop, assigning the same variable as many times as needed.

+2
source

Source: https://habr.com/ru/post/1500541/


All Articles