C#, List.Find() and Predicates

by admin on May 24, 2011 · 7 comments

This post was original posted on my personal site in October 2007, but it’s a better fit here and since it gets a bunch of visits every day I figured it’d be better to move it than kill it.  Enjoy, updates at the bottom.

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

Update, post-migration: In the comments on the original version, Vinit correctly pointed out that in later .NET versions you could just use

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

Which is a lot cleaner, and I never did get around to writing about lambda abuse, but seriously, it’s cool stuff.  The best way to learn how to refactor old C# code, in my opinion, is to get a copy of Resharper, which will make all kinds of suggestions.  Your old code will get cleaner, and you’ll be a faster programmer – obviously don’t go around refactoring everything blindly in a release that’s just supposed to have a spelling mistake fixed in it, but make the changes when test windows present themselves, and then just code in your old style and let Resharper help you get up to speed.

That’s not an affiliate link, I get no money from them, but I won’t use Visual Studio without that tool because consciously choosing to write without it is basically admitting that mediocrity is just find fine with you. (updated to preserve the epic typo LeroyGaman pointed out while clarifying the overall sentence… Yeeha!)

{ 7 comments… read them below or add one }

LeroyGaman May 31, 2011 at 9:30 pm

“I won’t use Visual Studio without that tool because consciously choosing to write without it is basically admitting that mediocrity is just find with you.”

I have the same theory about using Word without Grammar Check: but maybe mediocre English is just “find” with you.
:-)

admin May 31, 2011 at 10:13 pm

Oh snap, that’s awesome. I need a compiler for my word-things. :)

wloescher June 29, 2011 at 12:09 pm

Helpful nugget…thanks!

Fima September 25, 2011 at 6:01 am

thanks, you save me a lot of time

Fazi October 19, 2011 at 5:02 am

Charsi kahi ka

Vitaliy Kosteev From Siberia (Rus) December 21, 2011 at 3:27 am

Thank you!

muzi March 29, 2012 at 12:57 pm

love it “pure awesomeness” (referring to use of lambda expression)

Leave a Comment

Previous post:

Next post: