views:

67

answers:

4

I have a lambda selector, lets say Func<T, TResult>. Is it possible to convert it into a predictor (Func<T, bool>) using a TResult object as reference?

For example, convert

x => x.Name

into

x => x.Name == customerName
+1  A: 

Try this:

Func<Person, string> projection = x => x.Name;

Func<Person, bool> predicate = x => projection(x) == customerName;
Steven
+4  A: 

Something like this?

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

Usage:

Func<Foo, bool> myPredicate = CreatePredicate(x => x.Name, customerName);

Could you tell us a bit more about why you want to do this?

Ani
+1  A: 

I’ll assume that you meant

x => x.Name == customerName

because = is assignment and I think you want comparison.

The answer is:

static Func<T, bool> MakePredictor<T>(Func<T, string> lambda,
                                      string customerName)
{
    return x => lambda(x) == customerName;
}
Timwi
A: 
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);
}
_FRED_