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", "bed" }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With