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

ToDictionary() - for enumerations of groupings

Converts an IEnumerable<IGrouping<TKey,TValue>> to a Dictionary<TKey,List<TValue>> so that you can easily convert the results of a GroupBy clause to a Dictionary of Groupings. The out-of-the-box ToDictionary() LINQ extension methods require a key and element extractor which are largely redundant when being applied to an enumeration of groupings, so this is a short-cut.

Source

using System.Collections.Generic;
using System.Linq;

namespace SharedAssemblies.Core.Extensions
{
    // This class contains helper additions to linq.
    public static class EnumerableExtensions
    {
        /// <summary>
        /// Converts an enumeration of groupings into a Dictionary of those groupings.
        /// </summary>
        /// <typeparam name="TKey">Key type of the grouping and dictionary.</typeparam>
        /// <typeparam name="TValue">Element type of the grouping and dictionary list.</typeparam>
        /// <param name="groupings">The enumeration of groupings from a GroupBy() clause.</param>
        /// <returns>A dictionary of groupings such that the key of the dictionary is TKey type and the value is List of TValue type.</returns>
        public static Dictionary<TKey, List<TValue>> ToDictionary<TKey,TValue>(this IEnumerable<IGrouping<TKey,TValue>> groupings)
        {
            return groupings.ToDictionary(group => group.Key, group => group.ToList());
        }
    }
}

Example

Dictionary<string,List<Product>> results = productList.GroupBy(product => product.Category).ToDictionary();

Author: James Michael Hare (BlackRabbitCoder)

Submitted on: 21 okt. 2010

Language: C#

Type: System.Collections.Generic.IGrouping

Views: 29634