Home > c#, Code > List<object> Find with delegate

List<object> Find with delegate

Thought this was really cool.

I have a generic List of objects, for example:

List<User> users = GetAllUsers();

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:

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

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

Cheers

Advertisements
Categories: c#, Code
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: