ToDictionary()
Converts an IEnumerable<IGrouping<TKey,TValue>> from a GroupBy() clause to a Dictionary<TKey, List<TValue>>.
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 = products.GroupBy(product => product.Category).ToDictionary();
Author: James Michael Hare (BlackRabbitCoder)
Submitted on: 21 okt. 2010
Language: C#
Type: System.Collections.Generic.IEnumerable
Views: 5567