Linq already has a set of GroupBy methods for enumerable, which returns IEnumerable<IGrouping<TKey, TSource>>
. I dislike this return type because it means I have to do a where query everytime I want to find a group. I try to make something that returns a dictionary instead, as below:
public static class GroupByExtension
{
public static Dictionary<TKey, List<TSource>> GroupToDictionary<TSource, TKey>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector)
{
return source.GroupBy(keySelector).ToDictionary
(grouping => grouping.Key, grouping => grouping.ToList());
}
}
I can test it like this
List<int> list = new List<int>() { 1, 2, 33, 4, 20, 43, 21, 93, 26, 31, 113 };
Dictionary<int, List<int>> numbersGroup = list.GroupToDictionary(i => i / 10);
//group number by result of division by ten.
So, I can call numbersGroup[1], numbersGroup[3], etc. as opposed to the more clumsy and less efficient Where
's clauses if I only have IEnumerable<IGrouping<TKey, TSource>>
IEnumerable<IGrouping<int, int>> numbersGroup2 = list.GroupBy(i => i / 10);
IGrouping<int, int> group =
numbersGroup2.Where(grouping => grouping.Key == 3).First();
//and this only returns an IGrouping, not a proper list,
//and where can be expensive for large list because it uses O(n) IIRC
//the first() could have also been avoided because we know that the keys are unique
What do you think of this code? What drawback do you see? And what is the reason Microsoft use IEnumerable<IGrouping<TKey, TSource>>