Print Page | Close Window

Filter with PredicateBuilder

Printed From: IdeaBlade
Category: DevForce
Forum Name: DevForce 2010
Forum Discription: For .NET 4.0
URL: http://www.ideablade.com/forum/forum_posts.asp?TID=2524
Printed Date: 29-Jul-2026 at 4:58pm


Topic: Filter with PredicateBuilder
Posted By: cgallant
Subject: Filter with PredicateBuilder
Date Posted: 21-Feb-2011 at 12:08pm

Hello,

I have been working with my PagedCollectionView by setting its filter which then changes my data grid on my page. The filter is set by changing values in combo boxes on my form.

PagedCollectionView  empListView = new PagedCollectionView(employees);
empListView.Filter = new Predicate<object>(DoFilter);


private bool DoFilter(object o)
{
           Employee emp = o as Employee;
            If (emp != null)
            {
                  if( cboEmployeeState.Text  != “” )
                  {
                                   if( cboEmployeeTitle.Text  != “” )
                                   {
                                                return true;
                                    }
                                    return true;
                   }
                  elseif( cboEmployeeTitle.Text  != “” )
                  {
                       return true;
                   }
                   else
                   {
                       return false;
                    }
            }
            return false;
}


Can i return an answer using the PredicateBuilder that the PageCollectionView can use? I looked in the forums and found this.

Expression<Func<SIGN, bool>> p1, p2, checkP;
if (cboEmployeeState.Text != "")
     p1 = p => p.State.Contains("Ohio");
if (cboEmployeeTitle.Text  != "")
     p2 = p => p.Title.Contains("Manager");
    
checkP = PredicateBuilder.Or(p1, p2);


But i can not figgure out how to make the PageCollectionFilter use this or if even can be done.

Thanks, for any help,
Craig

 




Replies:
Posted By: DenisK
Date Posted: 21-Feb-2011 at 6:23pm
Hi cgallant;

This is actually pretty tricky and not as straight forward as we would have hoped. Please see the code sample below.

var p1 = PredicateBuilder.Make(typeof(Category), "CategoryName", FilterOperator.Contains, "Produce");
        var predicate = p1.ToPredicate<Category>();
        Func<Category, bool> someFunc = predicate.Compile();
        Predicate<object> filter = t => someFunc((Category)t);

        pcv.Filter = filter;

I was able to find the answer here.

http://stackoverflow.com/questions/3755617/how-do-i-dynamically-construct-a-predicate-method-from-an-expression-tree - http://stackoverflow.com/questions/3755617/how-do-i-dynamically-construct-a-predicate-method-from-an-expression-tree

Hope this helps.





Print Page | Close Window