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
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.
Context.Employees.ToList().Where(x => states.Contains(x.State))
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;
}
}