IngBond
IngBond

Reputation: 668

Expression Func with two input parameters for generic method

I want to integrate this expression

Expression<Func<Customer, string, bool>> paramCompareFunc = (cust, name) => cust.Company == name;

For this

private bool IsUnique<Entity>(DbSet<Entity> set, 
   string param, 
   Expression<Func<Entity, string, bool>> paramCompareFunc) 
where Entity : class
{
  var query = set.Where(paramCompareFunc); // how I can pass param to expression?
  // var query = set.Where(paramCompareFunc(param)); // error here
...

How I can pass the second parameter to the expression?
I want to define different compare expressions for different entities (they don't have any same name field) and to have a possibility to pass this expression into my generic function.

Upvotes: 0

Views: 1218

Answers (1)

Jeremy Lakeman
Jeremy Lakeman

Reputation: 11110

The "easy" way is by changing your api to use a factory method to build the Expression you actually need;

Expression<Func<Customer, bool>> GetCompareFunc(string name) => (cust) => cust.Company == name;

While you could use ReplacingExpressionVisitor to swap the name parameter with a constant, that would have a negative impact on performance.

Upvotes: 1

Related Questions