C#, List.Find() and Predicates

Because I use this just infrequently enough to have to look it up every time…

I’m a huge (ab)user of the .NET generic collection classes, but I hate cluttering code with foreach() loops every time that I need to find an item in a collection. Enter the Find() method, which takes a predicate and does the work for you so you can keep focusing on the stuff that’s actually interesting:

List<SomeObject> myObjects = new List<SomeObject>();
/* .. load objects up somehow .. */
SomeObject desiredObject =
    myObjects.Find(delegate(SomeObject o) { return o.Id == desiredId; });

Posted

in

by

Comments

7 responses to “C#, List.Find() and Predicates”

  1. Vinit Avatar
    Vinit

    With VS2008 (even with .NET 2.0), this can be rewritten as:

    SomeObject desiredObject = myObjects.Find( o => o.Id == desiredId);

    Even cleaner 🙂

  2. Jason Avatar
    Jason

    I’ve got a zillion imaginary posts in my head about the new lamda expressions – Sort routines are almost elegant now, especially if you ever had to deal with collection in 1.1! Thanks for helping keep this post relevant!

  3. Sebastian Avatar
    Sebastian

    Hello,

    Thanks for the example… but what if you have a hierarchical list (as in a TreeView) and you need to have the same TreeView.Find() method? Is it possible to implemented with delegates? Or you have to implement a recursive search on the list?

    Thanks!

  4. Jason Avatar
    Jason

    Hi Sebastian, I messed around with the TreeView for a while (the Windows Forms version, anyway) but didn’t have any luck. If your search is key based, your best bet seems to still be tree.Nodes.Find(key, true).

    Jason

  5. André Avatar
    André

    Thank you!

  6. Rodrigo Vaz Avatar
    Rodrigo Vaz

    Thanks a lot man !!!

  7. Bhupendra Avatar
    Bhupendra

    what is the difference between Find and Foreach if the List is of TreeNode type i.e. is there any performance difference or just a change in coding style?