Welcome to MSDN Blogs Sign in | Join | Help
Searching generic lists

A nice article posted by Jeff on using predicates to search generic lists. This can also be applied to other methods, such as Exists and TrueForAll etc. 

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.

Share this post: email it! | bookmark it! | digg it! | reddit! | kick it! | live it!

Source: Using an anonymous delegate in List.FindAll()

Posted: Saturday, March 24, 2007 3:46 AM by jasward
Filed under: ,

Comments

No Comments

Leave a Comment

(required) 

(required) 

(optional)

(required) 

  
Enter Code Here: Required

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Page view tracker