Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Query with Array input and variable Where Statements - Advice

Tags:

c#

linq

I would like to query data given an array to filter by via WCF Data Services using the Silverlight Client API. Basically, I want to query Employees given a list (array) of States.

I'm thinking something like this:

public IQueryable<Employee> Load(string[] states)
{
     foreach (var x in states)
     {
           // LINQ query here with 1 to N .Where statements
           return from e in Context.Employees
           .Where(...)
     }
} 

So let's say my array has 2 items in it, i.e. I want to query by 2 states, I would do something like this manually:

return from e in Context.Employees
    .Where(e => e.State== states[0] || e.State == states[1])));

Any advice will be greatly appreciated!

like image 536
user118190 Avatar asked Sep 11 '26 12:09

user118190


1 Answers

You can dynamically build the expression tree for the condition.

var parameter = Expression.Parameter(typeof(Employee), "employee");

Expression condition = Expression.Constant(false);

foreach (var state in states)
{
    condition = Expression.OrElse(
        condition,
        Expression.Equal(
            Expression.Property(parameter, "State"),
            Expression.Constant(state)));
}

var expression = Expression.Lambda<Func<Employee, Boolean>>(condition, parameter);

And then just perform the call.

var result = Context.Employees.Where(expression);

I am not 100% sure if this will work out of the box for you but I hope the general idea helps.

like image 184
Daniel Brückner Avatar answered Sep 14 '26 02:09

Daniel Brückner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!