如何使用条件三元运算符分配Func <>?

Stu*_*tLC 5 c# lambda func

我知道Func<>s不能通过var关键字直接隐式输入,尽管我希望我可以执行以下谓词赋值:

Func<Something, bool> filter = (someBooleanExpressionHere)
   ? x => x.SomeProp < 5
   : x => x.SomeProp >= 5;
Run Code Online (Sandbox Code Playgroud)

但是,我得到了错误 cannot resolve the symbol, 'SomeProp'

目前,我已经采取了更加繁琐的if branch任务,这似乎并不优雅.

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

我错过了什么,或者我是否需要坚持使用if-branch作业?

Lee*_*Lee 10

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

  • 是的,因此是“那种”。但至少我不必拼写我的 lambda 签名*两次*! (2认同)