我想使用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(...)
}
}
所以,假设我的数组中有2个项目,即我想通过2个状态进行查询,我会手动执行以下操作:
return from e in Context.Employees
.Where(e => e.State== states[0] || e.State == states[1])));
任何建议都将不胜感激!
答案 0 :(得分:5)
您可以为条件动态构建表达式树。
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);
然后只是进行通话。
var result = Context.Employees.Where(expression);
我不是百分百肯定,如果这对你来说是开箱即用的,但我希望这个概念有所帮助。
答案 1 :(得分:1)
Context.Employees.ToList()。Where(x =&gt; states.Contains(x.State))
答案 2 :(得分:0)
这是一个可运行的例子,可以做你想要的,我想?给定状态列表,它将为您提供处于这些状态的员工。
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;
}
}