user118190
user118190

Reputation: 2179

LINQ Query with Array input and variable Where Statements - Advice

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!

Upvotes: 3

Views: 3840

Answers (3)

Daniel Br&#252;ckner
Daniel Br&#252;ckner

Reputation: 59645

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.

Upvotes: 5

Tim Coker
Tim Coker

Reputation: 6524

Here's a runnable example that does what you want, I think? Given a list of states, it will give you the employees that are in those states.

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> states = new List<string>();
            states.Add("SC");
            states.Add("TX");
            states.Add("NC");

            List<Employee> emps = new List<Employee>();
            emps.Add(new Employee() { State = "GA", Name = "Bill" });
            emps.Add(new Employee() { State = "TX", Name = "John" });
            emps.Add(new Employee() { State = "SC", Name = "Mary" });

            //Here's where the work is done.  The rest is fluff...
            var empsinstates = from e in emps where states.Contains(e.State) select e;

            foreach (var e in empsinstates)
            {
                Console.WriteLine(e.Name + " " + e.State);
            }
            Console.Read();
        }
    }
    class Employee
    {
        public string State;
        public string Name;
    }
}

Upvotes: 0

gmn
gmn

Reputation: 4319

Context.Employees.ToList().Where(x => states.Contains(x.State))

Upvotes: 1

Related Questions