ToDictionary() - for Enumerations of Groupings

Converts an IEnumerable<IGrouping<TKey,TValue>> to a Dictionary<TKey,List> 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.

源代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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());
}
}
}

示例:

1
Dictionary<string,List<Product>> results = productList.GroupBy(product => product.Category).ToDictionary();
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×