Here's the scenario:
Silverlight 4.0, DataGrid, PagedCollectionView itemssource.
The objective is to apply a Filter to the PCV. The filter needs to be a Predicate<object>(Method)
- where Method implements some logic against the object and returns true/false for inclusion.
What I have is a need to optionally include 3 different criteria in the filter logic and explicit code quickly gets ugly. We don't want that, do we?
So I see that there is a way to build an expression tree using PredicateBuilder and pass that into Linq.Where, a la:
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);
}
[this is not what I'm trying to do by the way]
With 3 optional criteria, I want to write something like:
Ratings.Filter = BuildFilterPredicate(); // Ratings = the PagedCollectionView
private Predicate<object> BuildFilterPredicate()
{
bool FilterOnOrder = !String.IsNullOrEmpty(sOrderNumberFilter);
var predicate = PredicateBuilder.False<object>();
if (ViewMineOnly)
{
predicate = predicate.And(Rating r => sUserNameFilter == r.Assigned_To);
}
if (ViewStarOnly)
{
predicate = predicate.And(Rating r => r.Star.HasValue && r.Star.Value > 0);
}
if (FilterOnOrder)
{
predicate = predicate.And(Rating r => r.ShipmentInvoice.StartsWith(sOrderNumberFilter));
}
return predicate;
}
Of course this won't compile because PredicateBuilder creates an Expression<Func<T, bool>>
not an actual predicate method. But I see that there are ways to convert an expression tree into a method so it seemed to me there ought to be a way to accomplish what I'm after without resorting to a bunch of nested if/then/else statements.
So the question is - is there a way to build a predicate method dynamically?
TIA