Composing a where clause in LINQ query at runtime
I'm getting an array of strings for which I want to see if a certain number of data fields in the domain object have all of those strings. I know the data fields at compile-time but I don't know the size of the array at compile-time.
Is there a way that I can compose a where clause at run-time so that I can do what I'm looking for in a single linq query.
If you're wondering why it's a single query: I want to reduce the round trips to the DB as much as possible.
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
}
The end result is, given 2 objects:
domainObject { Address = "1st st", Description="has couch and bed" }
domainObject2 { Address = "1st rd", Description="has couch" }
A query for { "couch", "bed" }
would only return domainobject 1 but a query for { "couch" }
would return both.
Likeqise a query for { "1st", "couch", "b开发者_Go百科ed" }
would return both as well.
You should use PredicateBuilder, it is a free utility class that allows you to construct complex where clauses using And's and Or's at runtime. You can loop through your array and build your where clause that way.
http://www.albahari.com/nutshell/predicatebuilder.aspx
There's 3 main ways to do it, PredicateBuilder, Dynamic Linq library, or manipulating your own Expression Trees (which the first two help you do under the covers).
PredicateBuilder is your best bet if you know all the properties in advance. If they are dynamic (i.e. the user selects them, then Dynamic Linq is the best bet).
See also Is there a pattern using Linq to dynamically create a filter?.
link text
精彩评论