Jason

C#, List.Find() and Predicates

by Jason on October 30, 2007

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; });

{ 7 comments }

Vinit July 21, 2008 at 7:17 pm

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

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

Even cleaner :)

Jason July 22, 2008 at 7:35 pm

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!

Sebastian July 29, 2008 at 11:28 am

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!

Jason August 12, 2008 at 1:56 pm

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

André November 17, 2008 at 10:53 am

Thank you!

Rodrigo Vaz December 3, 2008 at 5:40 am

Thanks a lot man !!!

Bhupendra December 23, 2008 at 4:18 am

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?