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.


