#me { float: left; }

March 19, 2008

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

Filed under: C#, Object Orientated Programming, Programming — Simon Rigby @ 1:47 am

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.

Theme: WordPress Classic. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.