我得到一个字符串数组,我想查看域对象中的某些数据字段是否包含所有这些字符串。我在编译时知道数据字段,但在编译时我不知道数组的大小。在运行时在LINQ查询中编写where子句
有没有一种方法可以在运行时编写where子句,以便我可以在单个linq查询中执行所需的操作。
如果您想知道为什么只有一个查询:我想尽可能减少往返数据库的往返行程。
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
}
最终的结果,给定2个对象:
domainObject { Address = "1st st", Description="has couch and bed" }
domainObject2 { Address = "1st rd", Description="has couch" }
一种用于{ "couch", "bed" }
查询将只返回domainObject的1但对于{ "couch" }
查询将返回两者。
赞同查询{ "1st", "couch", "bed" }
将同时返回。
在设计时是否已知域对象的属性?如果不反思可能是你最好的选择。如果是这样,您可以公开您的域对象的可搜索字段的IEnumerable。 –
2010-09-10 20:39:44
关于“单个查询”:您可以在多个C#语句中编写查询,并且在执行(db读取)方面它仍然是单个查询。阅读“延期执行”了解原因。 – Marcel 2012-11-02 08:56:03