Duplicate
I can do this:
Func<CategorySummary, decimal> orderByFunc;
if (orderBy == OrderProductsByProperty.Speed)
orderByFunc = x => x.Speed;
else
orderByFunc = x => x.Price;
Why can't I do this:
Func<CategorySummary, decimal> orderByFunc = (orderBy == OrderProductsByProperty.Speed) ? x => x.Speed : x => x.Price;
The 'type inference' on the conditional operator is not quite good enough, I get a message like
Type of conditional expression cannot be determined because there is no implicit conversion between 'lambda expression' and 'lambda expression'
you can always just be explicit on the right-hand-side, a la
var o = true ? new Func<int,int>(x => 0) : new Func<int,int>(x => 1);
In any case it's just a minor annoyance regarding how the types of lambdas, type inference, and the conditional operator interact.
Just cast the lambda's to Func<CategorySummary, decimal>
and it will work
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