Using Predicate Delegate
Predicate Delegate is an new feature in 2.0.Normally if we want to search for an item in a Array or in an Objectlist we prefer using foreach statement for iterating thro' the list.The use foreach statement normally makes the code messy and confusing, leaving with some performance issue.Now here come the use of Predicate delegate.As a definition we can say predicate delegate is a method that defines set of criteria and determines whether a object obeys the criteria.
The synatax for Predicate method should be like,
public delegate bool Predicate (
T obj
)
The method should return true,if the criteria is satisfied else it should be false.
I am having array of names and to search for a name that starts with "S",the predicate method will be,
public static bool Search(string str) {
return str.StartsWith("S", StringComparison.InvariantCultureIgnoreCase);
}
To use this Predicate method for Searching,
Array.Find(str, Search);
here "str" is the array that holds the names.
As i said predicates can be used with Array and List,where in our example it will be,
Array.Find(str, Search);
for a array and for List,
emplist.Find(SearchList);
Here,"emplist" is the Generic list that holds list of Employee entity.
Note: We need not declare the delegate explicitly in case C# and VB because the compilers themselves figures it out using the Predicate methods.
You can find the attached examples for using predicates for Array and Generic List.
Download Source
Predicate Delegate is an new feature in 2.0.Normally if we want to search for an item in a Array or in an Objectlist we prefer using foreach statement for iterating thro' the list.The use foreach statement normally makes the code messy and confusing, leaving with some performance issue.Now here come the use of Predicate delegate.As a definition we can say predicate delegate is a method that defines set of criteria and determines whether a object obeys the criteria.
The synatax for Predicate method should be like,
public delegate bool Predicate
T obj
)
The method should return true,if the criteria is satisfied else it should be false.
I am having array of names and to search for a name that starts with "S",the predicate method will be,
public static bool Search(string str) {
return str.StartsWith("S", StringComparison.InvariantCultureIgnoreCase);
}
To use this Predicate method for Searching,
Array.Find(str, Search);
here "str" is the array that holds the names.
As i said predicates can be used with Array and List,where in our example it will be,
Array.Find(str, Search);
for a array and for List,
emplist.Find(SearchList);
Here,"emplist" is the Generic list that holds list of Employee entity.
Note: We need not declare the delegate explicitly in case C# and VB because the compilers themselves figures it out using the Predicate methods.
You can find the attached examples for using predicates for Array and Generic List.
Download Source



0 Comments:
Post a Comment
<< Home