具有数组输入和变量Where语句的LINQ查询-建议 [英] LINQ Query with Array input and variable Where Statements - Advice

查看:47
本文介绍了具有数组输入和变量Where语句的LINQ查询-建议的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想查询给定数组的数据,以使用Silverlight Client API通过WCF数据服务进行过滤.基本上,我想查询给出状态列表(数组)的Employees.

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.

我在想这样的事情:

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个状态进行查询,那么我会手动执行以下操作:

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])));

任何建议将不胜感激!

推荐答案

我想这是一个可运行的示例,它可以满足您的需求?给定州列表,它将为您提供这些州的员工.

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;
    }
}

这篇关于具有数组输入和变量Where语句的LINQ查询-建议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆