Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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", "bed" } would return both as well.

like image 895
Steven Evers Avatar asked Oct 15 '22 00:10

Steven Evers


1 Answers

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

like image 200
luksan Avatar answered Oct 27 '22 09:10

luksan