Home > Development > Enumerable extensions to remove duplicates with a function return the key value

Enumerable extensions to remove duplicates with a function return the key value

September 22, 2010 Leave a comment Go to comments

Wow.. Long title…

If you have an enumerable and you want to remove duplicates out of the list with a function that returns the key of the type use the extension method I have developed below. Really handy 🙂

public static class EnumerableExtensions
    {
        public static IEnumerable<ElementType> EnsureDuplicateAreRemoved<ElementType,TKeyType>
            (this IEnumerable<ElementType> enumerable, Func<ElementType, TKeyType> keyProducer)
        {
            Dictionary<TKeyType, TKeyType> cache = new Dictionary<TKeyType, TKeyType>();

            foreach (var element in enumerable)
            {
                var value = keyProducer(element);
                if(cache.ContainsKey(value))
                    continue;
                cache.Add(value,value);
                yield return element;
            }

        }
    }

Blair…

Advertisements
  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: