List<object> Find with delegate

Thought this was really cool.

I have a generic List of objects, for example:

[csharp]List<User> users = GetAllUsers();[/csharp]

I want to find a user by username. Usually you would loop through looking for the item with the matching username and return the user that was found.

or you could do this:

[csharp]User loggedOnUser = users.Find(delegate(User u) { return u.Username == "jbloggs"; });[/csharp]

Much less code, and you could match on any property of the object that you wanted.

Cheers

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.