Dynamic where clause in LINQ - with column names available at runtime

Posted by sandesh247 on Stack Overflow See other posts from Stack Overflow or by sandesh247
Published on 2008-10-24T17:13:57Z Indexed on 2012/04/05 5:30 UTC
Read the original article Hit count: 200

Filed under:
|
|

Disclaimer: I've solved the problem using Expressions from System.Linq.Expressions, but I'm still looking for a better/easier way.

Consider the following situation :

var query = 
    from c in db.Customers
    where (c.ContactFirstName.Contains("BlackListed") || 
           c.ContactLastName.Contains("BlackListed")  ||
           c.Address.Contains("BlackListed"))
    select c;

The columns/attributes that need to be checked against the blacklisted term are only available to me at runtime. How do I generate this dynamic where clause?

An additional complication is that the Queryable collection (db.Customers above) is typed to a Queryable of the base class of 'Customer' (say 'Person'), and therefore writing c.Address as above is not an option.

© Stack Overflow or respective owner

Related posts about .NET

Related posts about linq-to-sql