LINQ Query with Array input and variable Where Statements - Advice

前端 未结 3 1475
予麋鹿
予麋鹿 2021-01-20 03:25

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

相关标签:
3条回答
  • 2021-01-20 03:57

    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.

    0 讨论(0)
  • 2021-01-20 04:00

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

    0 讨论(0)
  • 2021-01-20 04:07

    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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题