Hi
Predicate are type of filter which can filter data based on certain criteria. Predicate is a generic delegate which represents a method that defines a set of criteria to filter records in a generic list.
Lets take an example of a generic list of string.
List<string> strName = new List<string>();
Now let say we want to fetch those data which starts with V. Without predicate we would write something like the code below.
for (int i = strName.Count - 1; i >= 0; i--)
{
if (!strName [i].StartsWith("V"))
{
strName.RemoveAt(i);
}
}
Predicate can help us separate the logic and hence make things reusable. With predicates we can separate the logic to some other function and write code like the below to do the same work.
bool IsNonHttp(string strName)
{
return !strName.StartsWith("A");
}
strName.RemoveAll(IsNonHttp);
This can be very useful if you want to separate the logic and reuse it. Also the code looks neater when we use predicate. Some of the other methods where we can use a predicate are
List.Exists()
List.Find()
List..FindAll()
List..FindIndex()
List..FindLast()
List.findLastIndex()
List.TrueforAll()
Vikram