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 http://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); } }

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

matcher =

new ListMatcher

(

"QA"

);

this

.FindAll(matcher.Predicate);

Done.:)