在运行时在LINQ查询中编写where子句

Ste*_*ers 5 c# linq where-clause

我正在获取一个字符串数组,我想看看域对象中的一定数量的数据字段是否具有所有这些字符串.我在编译时知道数据字段,但我不知道编译时数组的大小.

有没有一种方法可以在运行时组成一个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
}
Run Code Online (Sandbox Code Playgroud)

最终结果是,给出了2个对象:

domainObject  { Address = "1st st", Description="has couch and bed" }
domainObject2 { Address = "1st rd", Description="has couch" }
Run Code Online (Sandbox Code Playgroud)

查询{ "couch", "bed" }只返回domainobject 1,但查询{ "couch" }将返回两者.

Likeqise查询{ "1st", "couch", "bed" }也将同时返回.

luk*_*san 2

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

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