我想查询给定数组的数据,以使用Silverlight客户端API通过WCF数据服务进行筛选.基本上,我想查询给定列表(数组)状态的Employees.
我在想这样的事情:
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(...)
}
}
Run Code Online (Sandbox Code Playgroud)
所以,假设我的数组中有2个项目,即我想通过2个状态进行查询,我会手动执行以下操作:
return from e in Context.Employees
.Where(e => e.State== states[0] || e.State == states[1])));
Run Code Online (Sandbox Code Playgroud)
任何建议将不胜感激!
您可以为条件动态构建表达式树.
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);
Run Code Online (Sandbox Code Playgroud)
然后只是执行调用.
var result = Context.Employees.Where(expression);
Run Code Online (Sandbox Code Playgroud)
我不是100%肯定这是否会制定出适合您的箱子,但我希望的总体思路帮助.