MSDN Says : Predicate delegate Represents the method that defines a set of criteria and determines whether the specified object meets those criteria.
We can use this functionality when filtering any collection object which satisfy certain condition.
Here is an example how to use it in our application. In this example we will see different ways of removing all odd number from list of items using predicate.
Create the list of first 30 number.
// ....... List lstNumbers = new List(); for (int i = 0; i < 30; i++) { lstNumbers.Add(i); } 1. Normal way (Without using predicate) for (int i = 0; i < lstNumbers.Count;i++ ) { if (lstNumbers[i] % 2 != 0) { lstNumbers.RemoveAt(i); } }
Here we are traversing through each item manually and checking the condition for each item.
2. Writing the delegate function inline.
We can write the delegate function inline which will check the condition and return the result. And we can provide that directly to the function.
lstNumbers.RemoveAll(delegate(int arg) { if (arg % 2 == 0){ return true; } else {return false; } });
3. Using Predicate (Creating delegate function)
Creating a function which will check the condition and return the result.
bool isOdd(int n) { if (arg% 2 != 0) { return true; } else { return false; } }
Calling that function name inside the method that accepts predicate as an argument.
lstNumbers.RemoveAll(isOdd);
Or
instead of the above line we can create a predicate object which refers to the isOdd() function. And we can use this object to filter out the condition by specifying it in the argument of method call.
Predicate predEven = new Predicate(isOdd); lstNumbers.RemoveAll(predEven);
Advantages : In the last approach your code will be elegant and reusable.
Some more function which use predicate as arguments are :
List.Exists List.Find List.TrueForAll
These function check, if the condition defined in the predicate is matching or not and return the result accordingly.