代码之家  ›  专栏  ›  技术社区  ›  Steven Evers

在运行时在LINQ查询中组合where子句

  •  5
  • Steven Evers  · 技术社区  · 14 年前

    我得到了一个字符串数组,我想看看域对象中特定数量的数据字段是否包含所有这些字符串。我知道编译时的数据字段,但不知道编译时数组的大小。

    有没有一种方法可以在运行时编写where子句,这样就可以在单个linq查询中执行所需的操作。

    如果您想知道为什么这是一个单一的查询:我想尽可能减少到DB的往返次数。

    public IEnumerable<domainObjects> GetObjectsWith(string[] data)
    {
        var results = from d in domainObjects
                      where 
                      (d.Data.Contains(data[0]) && d.Data.Contains(data[1]) && ...)
                      ||
                      (d.Data2.Contains(data[0]) && d.Data.Contains(data[1]) && ...)
                      .
                      .
                      . // Data fields known at compile-time
    }
    

    最终结果是,给定两个对象:

    domainObject  { Address = "1st st", Description="has couch and bed" }
    domainObject2 { Address = "1st rd", Description="has couch" }
    

    查询 { "couch", "bed" } { "couch" } 两者都会返回。

    像查询 { "1st", "couch", "bed" } 也会同时返回。

    3 回复  |  直到 14 年前
        1
  •  2
  •   luksan    14 年前

    您应该使用PredicateBuilder,它是一个免费的实用程序类,允许您在运行时使用And和Or构造复杂的where子句。您可以循环遍历数组并以这种方式构建where子句。

    http://www.albahari.com/nutshell/predicatebuilder.aspx

        2
  •  2
  •   Community CDub    8 年前

    主要有3种方法,PredicateBuilder、dynamiclinq库,或者操纵您自己的表达式树(前两种方法可以帮助您在幕后完成)。

    如果您事先知道所有属性,那么PredicateBuilder是您的最佳选择。如果它们是动态的(即用户选择它们,那么动态Linq是最佳选择)。

    Is there a pattern using Linq to dynamically create a filter? .

    link text