如何将 linq 选择器转换为预测器

Roy*_*Roy 1 c# generics lambda delegates

我有一个 lambda 选择器,可以说Func<T, TResult>. 是否可以Func<T, bool>使用TResult对象作为参考将其转换为预测器 ( ) ?

例如,转换

x => x.Name
Run Code Online (Sandbox Code Playgroud)

进入

x => x.Name == customerName
Run Code Online (Sandbox Code Playgroud)

Ani*_*Ani 5

像这样的东西?

static Func<TInput, bool> CreatePredicate<TInput, TResult>(Func<TInput, TResult> selector, TResult comparisonValue)
{
    return tInput => selector(tInput).Equals(comparisonValue);
}
Run Code Online (Sandbox Code Playgroud)

用法:

Func<Foo, bool> myPredicate = CreatePredicate(x => x.Name, customerName);
Run Code Online (Sandbox Code Playgroud)

你能告诉我们更多关于你为什么要这样做吗?