How to find one or more elements in a list (C#)

Let's assume we have a class called MyPrettyClass, with an int property called PrettinessFactor.

If we have a list of MyPrettyClass objects, in order to find the one with a PrettinessFactor of ten we write the following code:

//first we have to define a predicate
//which returns true if our condition is fulfilled
private bool FindItemWithPFTenPredicate(MyPrettyClass myClass)
{
return (myClass.PrettinessFactor == 10);
}

//find our element
...
List list = new List;
//class is filled
...
MyPrettyClass myItem = list.Find(new Predicate (FindItemWithPFTenPredicate));
...


Note that if we have more than one item in the list Find will only return the first one. If you need all of them FindAll should be used instead.

...
List myItems = list.FindAll(new Predicate (FindItemWithPFTenPredicate));
...

No comments: