Is it possible to choose which function to apply in Linq?
Example of what I now have:
List<int> list = new List<int>();
bool bDescend = false;
var listOrdered = bDescend ? list.OrderByDescending(it => it) :
list.OrderBy(it => it);
You see that I choose which function to apply depending on bDescend value – so there is actually two Linq queries, not one.
Is it possible to avoid it by putting condition inside one query?
Maybe something like
list.ChooseFunction(bDescend ? OrderBy : OrderByDescending)...
Real code is more compliated and if such trick possible it would make code much more readable.
Looks like kind of metaprogramming..
You could create your own Extension method:
And then call it like
Other than that, it’s possible to make a
ChooseFunctiontype thing, but it’d have to look likeChooseFunction(bdescend ? "OrderBy" : "OrderByDescending")and I don’t even want to get into how ugly those magic strings referring to function names are. You’d also have to either hard code the ChooseFunction extension, or rely on reflection which is ridiculously expensive for the simple thing you’re trying to do