2

Take Northwind as example.

My goal is to use Linq to Entity to search Employees dynamically.

My expression maybe:

Expression<Func<Employee, bool>> exp= em => em.EmployeeID > 2;

Here the operator '>' is selected by combobox at runtime, and it may be '<', '=', '<>', 'contains' and so on.

My question is, how to build the expression dynamically with the operator selected?

One important thing, no selective statements allowed, such as 'if' and 'switch'.

Any answer is appreciated.

Lei Yang
  • 3,970
  • 6
  • 38
  • 59

2 Answers2

0

If conditionals inside your lambda look unsightly to you, you can use a function

Expression<Func<Employee, bool>> exp= em => foo(em, otherParam);

public static bool foo(Employee em, otherType otherParam)
{
    ...
}
0

I would create a class that has a Func<Employee, bool> and overrides the ToString method to represent the operator that the function is using. Then, I would use an ObservableCollection of that class as the ItemsSource of your ComboBox.

Call your class Operator, and your code to perform the operation becomes:

var op = dropDown.SelectedItem as Operator;

if (op != null)
{
  op.Function(employee);
}
Luke Willis
  • 8,429
  • 4
  • 46
  • 79