Determine if an item exists in a generic list using a delegate

Let’s say for example you have a generic list of integers (List<int>) and before you add an item you must check to make sure its not already contained in the list. The solution is quite simple using an inline delegate.

Take myIDs to be a generic list of type int (List<int>) and myInt is some integer we are trying to add but only after making sure it not already in myIDs.

if (!myIDs.Exists(delegate(int i) { return i == myInt; })) 
{
    myIDs.Add(myInt);
}

The delegate effectively substitutes the argument (i) as a kind of placeholder. Exists effectively compares each item in the list and represents it as (i). Then for each i it checks to see if it equates to the passed in value (myInt). If the item exists (i == myInt) the method returns true and as a result the if block is not executed (i.e. not added).

Hope this helps.

Advertisements

4 thoughts on “Determine if an item exists in a generic list using a delegate

  1. You might want to go to your blog settings and uncheck the box so WordPress doesn’t automatically replace ;) and :) with emoticon images.

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