我有一个lambda选择器,让我们说Func<T, TResult>
。是否可以使用Func<T, bool>
对象作为参考将其转换为预测变量(TResult
)?
例如,转换
x => x.Name
到
x => x.Name == customerName
答案 0 :(得分:4)
这样的东西?
static Func<TInput, bool> CreatePredicate<TInput, TResult>(Func<TInput, TResult> selector, TResult comparisonValue)
{
return tInput => selector(tInput).Equals(comparisonValue);
}
用法:
Func<Foo, bool> myPredicate = CreatePredicate(x => x.Name, customerName);
你能告诉我们你为什么要这么做吗?
答案 1 :(得分:1)
试试这个:
Func<Person, string> projection = x => x.Name;
Func<Person, bool> predicate = x => projection(x) == customerName;
答案 2 :(得分:1)
我认为你的意思是
x => x.Name == customerName
因为=
是作业,我认为你想要进行比较。
答案是:
static Func<T, bool> MakePredictor<T>(Func<T, string> lambda,
string customerName)
{
return x => lambda(x) == customerName;
}
答案 3 :(得分:0)
static Predicate<T> Predicate<T, TResult>(Func<T, TResult> selector, TResult value) {
return Predicate(selector, value, EqualityComparer<TResult>.Default);
}
static Predicate<T> Predicate<T, TResult>(Func<T, TResult> selector, TResult value, IEqualityComparer<TResult> comparer) {
if(selector == null) {
throw new ArgumentNullException("selector");
} else if(comparer == null) {
throw new ArgumentNullException("comparer");
}
return x => comparer.Equals(selector(x), value);
}