Vadim's Weblog

Never stop learning.

Using Predicate delegate

Posted by Vadim on September 4, 2007

Have you ever try to find an element in the List or Array.   I’ve done it many times.  However, every time I have to look for an element inside a List I don’t remember how to do it and I have to either Google or search my own code.

This time I have to FindLast element in my List and I don’t remember how to do that.  So I decided to put it here so next time I know where to find an example.

[Test]
public void PredicateExample()
{
    List<string> myLst = new List<string>(
        new string[] { "elem1", "elem2", "elem3" });
    string elem = myLst.Find(delegate(string elemInSearch) 
        { return elemInSearch == "elem2"; });
    Assert.AreEqual("elem2", elem);
}

You also can create predicate delegate as separate method:

[Test]
public void AnotherPredicateExample()
{
    List<string> myLst = new List<string>(
        new string[] { "elem1", "elem2", "elem3" });
    string elem = myLst.Find(FindElement("elem2"));
    Assert.AreEqual("elem2", elem);
}
 
private Predicate<string> FindElement(string elem)
{
    return delegate(string listElem)
       {
           return listElem.Equals(elem);
       };
}

I hope it helps you.  It definitely is going to help me.

One Response to “Using Predicate delegate”

  1. alexander said

    Thanks a lot, it was really useful for me!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: