views:

88

answers:

3

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.

+2  A: 

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

luksan
+2  A: 

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 http://stackoverflow.com/questions/30879/is-there-a-pattern-using-linq-to-dynamically-create-a-filter.

link text

Richard Hein