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 SprintBacklogItem 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 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.:)

3 Comments

  • I beleive the same thing can be achieved with the use of an anonymous delegate. And then can be further simplified with lambda expressions...

    public List FindByTitle(string title)
    {
    this.FindAll(delegate(SprintBacklogItem item) { return item.Title.StartsWith(title, StringComparison.InvariantCultureIgnoreCase); });

    //// lambda
    this.FindAll(i => i.Title.StartsWith(title, ...));
    }

  • Can you just do

    string _HeaderToSearch = "QA";

    this.FindAll(delegate(SprintBacklogItem item)
    {
    return item.Title.StartsWith(_HeaderToSearch, StringComparison.InvariantCultureIgnoreCase);
    });

    to save you an extra class?

  • Yep :) . The same thing can be achieved using an anonymous delegate. I just wanted to show it without using Anonymous Delegate. :)

    /Adil

Comments have been disabled for this content.