tags:

views:

962

answers:

2

I am being passed a set of querystring parameters within a Parameters class with which to query an image database. With each call some parameters may by null. So in sql I would build up the query like

if (parameters.Value1 != null)
{
    sql.Append("sql_where_clause");
}

if (parameters.Value2 != null)
{
    sql.Append("sql_where_clause");
}

How do I do the same using Linq?

+5  A: 

easy, IQueryables aren't evaluated until you enumerate, so simply keep tagging on where clauses.

if (parameters.Value1 != null)
{
    results = results.Where(x => <some condition>);
}

if (parameters.Value2 != null)
{
    results = results.Where(x => <some other condition>);
}
Andrew Bullock
Note that this only really works for `AND`ing predicates.
Pete Montgomery
+5  A: 

The best way to dynamically build where-clauses is to use the wonderful Albahari PredicateBuilder.

You can use this to build where-clause expressions containing OR as well as AND. Language-integrated support for this was originally intended but didn't quite make it into C# 3.

For example:

var whereClause = PredicateBuilder.False<Customer>();

if (parameters.Value1 != null)
{
    whereClause = whereClause.Or(customer => customer.City == parameters.Value1);
}

var query = db.Customers.Where(whereClause);
Pete Montgomery
This made/saved my day. Thanks. And I was thinking that I just didnt get Linq to sql, as I just started using it..but alas the link above to PredicateBuilder was great! :) This definately is something that should be there??
Brian