Md. Adil Akhter's Weblogs

Me, My Thoughts and My Journey ....

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

Posted: Apr 18 2008, 04:34 PM by Adil Akhter | with 4 comment(s)
Filed under: ,

Comments

Ben said:

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<SprintBacklogItem> FindByTitle(string title)

{

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

   //// lambda

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

}

# April 18, 2008 8:04 PM

Tian said:

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?

# April 18, 2008 8:36 PM

David Findley said:

You can also use an anonymous delegate in C# 2.0 like this:

this.FindAll(

 delegate(SprintBacklogItem item) {

   return item.Title.StartsWith("QA", StringComparison.InvariantCultureIgnoreCase);

 }

);

Not quite as concise as lambdas in C# 3.0 but close.

# April 18, 2008 11:05 PM

Adil Akhter said:

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

/Adil

# April 19, 2008 4:23 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)