ExtensionMethod.NET Home of 875 C#, Visual Basic, F# and Javascript extension methods

ToDistinctDictionary

Creates an IDictionary<TKey, TValue> from the IEnumerable<TSource> instance based on the key selector and element selector. This is distinct by using the built-in index of the dictionary instance for either adding or updating a keys corresponding value.

Source

public static class EnumerableExtensions
{
    /// <summary>
    /// Creates a <see cref="T:System.Collections.Generic.Dictionary`2"/> from an 
    /// <see cref="T:System.Collections.Generic.IEnumerable`1"/> according to a specified 
    /// key selector function, and an element selector function.
    /// </summary>
    public static IDictionary<TKey, TElement> ToDistinctDictionary<TSource, TKey, TElement>(
        this IEnumerable<TSource> source,
        Func<TSource, TKey> keySelector,
        Func<TSource, TElement> elementSelector)
    {
        if (source == null) throw new NullReferenceException("The 'source' cannot be null.");
        if (keySelector == null) throw new ArgumentNullException("keySelector");
        if (elementSelector == null) throw new ArgumentNullException("elementSelector");

        var dictionary = new Dictionary<TKey, TElement>();
        foreach (TSource current in source)
        {
            dictionary[keySelector(current)] = elementSelector(current);
        }
        return dictionary;
    }
}

Example

var dictionary = someList.ToDistinctDictionary(li => li.Key, li => li);

Author: David Michael Pine

Submitted on: 10 nov 2014

Language: C#

Type: System.Collections.Generic.IEnumerable

Views: 4687