具有未知数量参数的Dynamic Where子句

时间:2014-03-14 20:34:30

标签: c# linq c#-4.0 dynamic linq-to-entities

我已经搜索了我的问题的答案,但一直找不到满足我需求的答案。

以下两个代码段返回相同的内容,我没有偏好使用哪一个,我只是包括两个以防它有助于某人回答我的问题

private List<MyClass> GetMyClass(string name, string city, string state, string zip)
{
    using (MyEntities ctx = new MyEntities())
    {
        var results = from a in ctx.MyEntity
                      where (a.Name == name &&
                             a.City == city &&
                             a.State == state &&
                             a.ZIP == zip)
                      select a;

        return results.ToList();
    }
}

private List<MyClass> GetMyClass(string name, string city, string state, string zip)
{
    using (MyEntities ctx = new MyEntities())
    {
        var results = ctx.MyEntity.Where(a => a.Name == name)
                                  .Where(a => a.City == city)
                                  .Where(a => a.State == state)
                                  .Where(a => a.ZIP == zip)
                                  .Select(a => a);

        return results.ToList();
    }
}

出于本示例的目的,假设我有一个搜索屏幕,要求用户输入姓名和城市;状态和ZIP是可选的。如有必要,查询必须至少搜索这两个字段以及任何其他字段。

显然,通过上面的示例,如果用户仅按名称和城市搜索,他们就不会得到任何结果,因为查询会尝试匹配State == null和ZIP == null,因为这两个参数未提供

如何重写此代码以仅搜索已提供参数的字段?

2 个答案:

答案 0 :(得分:2)

您可以将它们链接起来,例如:

var results = ctx.MyEntity.AsQueryable();

if(name != null)
    results = results.Where(a => a.Name == name);

// ... snip ...

if(zip != null)
    results = results.Where(a => a.ZIP == zip)

return results.ToList();

答案 1 :(得分:2)

var results = from a in ctx.MyEntity
              where ((a.Name == name || name == null) &&
                     (a.City == city || city == null) &&
                     (a.State == state || state == null) &&
                     (a.ZIP == zip) || zip == null)
              select a;