Passing Parameter to a Predicate in .Net2.0

In this post, we will see how to pass parameter to a method representing Predicate. 

Let’s say, we have a collection of SprintBacklogItems and we want to filter all the SprintBacklogItem with Title start’s with, let say “QA” or “Dev Task” depending on a input parameter. Now from the previous post https://adilakhter.wordpress.com/2008/01/11/using-predicate-actor-of-net20/  we know that , predicate only have 1 parameter of type T.

image

Then, how to pass a input parameter _HeaderToSearch in Predicate?

1. To do that, we need to a new object called ListMatcher –

public class ListMatcher 
   { 
       private string _HeaderToSearch; 
       public ListMatcher(string headerToSearch) 
       { 
           _HeaderToSearch = headerToSearch; 
       }  

       public bool Predicate(SprintBacklogItem item) 
       { 
           return item.Title.StartsWith(_HeaderToSearch, StringComparison.InvariantCultureIgnoreCase); 
       }  

   }  

2. Next , I initialized the ListMatcher object and use the HeaderToSearch  to filter the items- 

ListMatcher matcher = new ListMatcher("QA"); 
this.FindAll(matcher.Predicate);

Done.:)

Advertisement

5 thoughts on “Passing Parameter to a Predicate in .Net2.0”

  1. I guess that you can also do it like the following,

    public Predicate FilterHeaderBy(string header)
    {
    return item => item.Title.StartsWith(header, StringComparison.InvariantCultureIgnoreCase);
    }

    or

    public Predicate FilterHeaderBy(string header)
    {
    return new Predicate(
    delegate(SprintBacklogItem item)
    {
    item.Title.StartsWith(header, StringComparison.InvariantCultureIgnoreCase);
    }
    );
    }

    So we don’t need to create a new class for each predicate that we need in our application.

    Much more cleaner.

  2. Thanks. I redid it in simplified C# 3.0 style:

    public class ListMatcher
    {
    public string SearchFor;
    public bool StartsWith(string item)
    {
    return item.StartsWith(SearchFor,StringComparison.InvariantCultureIgnoreCase);
    }
    }
    this.FindAll(new ListMatcher {SearchFor = “QA”}.StartsWith);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: