views:

40

answers:

2

Hi,

Quick question on how to get even more out of PredicateBuilder. It works as per below:

IQueryable<Product> SearchProducts (params string[] keywords)
{
  var predicate = PredicateBuilder.False<Product>();

  foreach (string keyword in keywords)
  {
    string temp = keyword;
    predicate = predicate.Or (p => p.Description.Contains (temp));
  }
  return dataContext.Products.Where (predicate);
}

The question is, what if I would like to search by an arbitrary member as well, ie pass the function string[] as the keywords, but also the field to search by, eg fieldToSearch, and replace the p=> p.Description.Contains(temp)); with something allowing searching by fieldToSearch?

Is this possible, is it a bad idea?

+1  A: 

For what you want to do, Dynamic Linq might be more appropriate.

While writing type-safe queries is great for most scenarios, there are cases where you want the flexibility to dynamically construct queries on the fly. For example: you might want to provide business intelligence UI within your application that allows an end-user business analyst to use drop-downs to build and express their own custom queries/views on top of data.

Traditionally these types of dynamic query scenarios are often handled by concatenating strings together to construct dynamic SQL queries. Recently a few people have sent me mail asking how to handle these types of scenarios using LINQ. The below post describes how you can use a Dynamic Query Library provided by the LINQ team to dynamically construct LINQ queries.

http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

Robert Harvey
A: 

Why not have a separate method that takes an Expression<Func<Product,bool>> as a parameter. Then build the predicate outside the method and pass it as a parameter.

IQueryable<Product> SearchProducts (Expression<Func<Product,bool>> selector )
{
    return dataContext.Products.Where( selector );
}

used as

var selector = PredicateBuilder.False<Product>()
                               .Or( p => p.Name == name )
                               .Or( p => p.Vendor == vendor );

products = repository.SearchProducts( selector );
tvanfosson