How do I assign a Func <> using a conditional ternary operator?

I know it Func<>

cannot be implicitly injected directly with a keyword var

, although I rather hoped I could accomplish the following predicate assignment:

Func<Something, bool> filter = (someBooleanExpressionHere)
   ? x => x.SomeProp < 5
   : x => x.SomeProp >= 5;

      

However I am getting the error cannot resolve the symbol, 'SomeProp'

For now, I have resorted to a more cumbersome assignment if branch

, which doesn't seem so elegant.

Func<Something, bool> filter;
if (someBooleanExpressionHere)
{
    filter = x => x.SomeProp < 5;
}
else
{
    filter = x => x.SomeProp >= 5;
}

      

Am I missing something, or will I need to stick with the assignment of if-branch?

+3


source share


4 answers


var filter = (someBooleanExpressionHere)
   ? new Func<Something, bool>(x => x.SomeProp < 5)
   : x => x.SomeProp >= 5;

      



+7


source


You have to wrap them in new Func

, otherwise it won't be able to convert one lamdba to another:

 Func<Something, bool> filter = (someBooleanExpressionHere)
   ? new Func<Something, bool>(x => x.SomeProp < 5)
   : x => x.SomeProp >= 5
   ;

      



If you uninstall new Func...

, you get:

The type of the conditional expression cannot be determined because there is no implicit conversion between "lambda expression" and "lambda expression"

+3


source


You can explicitly specify the type as a hint to the compiler

var filter = (condition)
    ? (Func<Something, bool>)(x => x.SomeProp < 5)
   : x => x.SomeProp >= 5;

      

+1


source


You can assign these selectors to static fields as needed.

private static readonly Func<Something, bool> _someFilter = x => x.SomeProp < 5;
private static readonly Func<Something, bool> _someOtherFilter = x => x.SomeProp >= 5;

      

Then you can use them later.

var filter = (someBooleanExpressionHere) ? _someFilter : _someOtherFilter;

      

0


source







All Articles