An overview of use of predicate with generic List

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


Share this post   Email it |  digg it! |  reddit! |  bookmark it!

Feedback

Posted on 10/15/2007 12:08:48 AM

can u give me powerful coding tricks with some description or details

Posted on 11/8/2007 7:10:58 PM

We can find all the strings that starts with "A" using below single line.

strName.FindAll(delegate (string instance) { return instance.StartsWith("A"); });

Please post your comments:

Name:  
Email (optional): Your email address will not be posted.
URL (optional):
Comments: HTML will be ignored, URLs will be converted to hyperlinks  
Enter the text you see in the box:
 
Copyright © 2006 - 2009 Vikram Lakhotia