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.
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.:)
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.
Nice work
Missed return keyword inside delegate. Thanks Excellent work
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);
great!!