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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With