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 }
“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.
Oh snap, that’s awesome. I need a compiler for my word-things.
Helpful nugget…thanks!
thanks, you save me a lot of time
Charsi kahi ka
Thank you!
love it “pure awesomeness” (referring to use of lambda expression)