Using an anonymous delegate in List<T>.FindAll()
If your experience is anything like mine, you probably have been using generics like crazy since .NET v2 hit the streets (or before if you were a beta monkey). It's so much easier to manipulate object and especially strongly typed collections.
One thing I always found annoying, however, was that there wasn't an obvious way to find stuff in a List<T> object. For example, if you had a list of NavEntry objects that have Title and Url properties, there's no obvious way to pipe in some string and find all of your matches. The documentation tells you how to use a search predicate, which is not particularly useful in real life because you can't pass in parameters to it. You can of course use some private variable, but it feels "hackish" (for lack of a better word) and is less elegant.
A friend of mine, much smarter than me, suggested using an anonymous delegate. So in my example, you'd create a class like this:
public class NavEntryList : List<NavEntry>
{
public List<NavEntry> GetItemsContaining(string text)
{
return this.FindAll(delegate(NavEntry nav) { return nav.Title.Contains(text); });
}
}
I like the way that rolls much better. You can substitute the Title property for whatever it is your object has, and even create one for each property, if you'd like. You can probably refactor this even more. I've seen a third-party class library that does all kinds of neat stuff like this, though the name escapes me at the moment.