HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

What do you think of this improvement of Linq's GroupBy method?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thislinqyouwhatmethodgroupbyimprovementthink

Problem

Linq already has a set of GroupBy methods for enumerable, which returns IEnumerable>. 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> GroupToDictionary(
            this IEnumerable source,
            Func keySelector)
        {
            return source.GroupBy(keySelector).ToDictionary
                (grouping => grouping.Key, grouping => grouping.ToList());
        }
    }


I can test it like this

List list = new List() { 1, 2, 33, 4, 20, 43, 21, 93, 26, 31, 113 };
Dictionary> 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>

IEnumerable> numbersGroup2 = list.GroupBy(i => i / 10);
IGrouping 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>

Solution

I think the reason it's done this way is to make GroupBy() consistent with the rest of LINQ: everything is as lazy as possible, so that following queries can be efficient.

And there already is a method that does almost the same thing as your GroupToDictionary(), it's called ToLookup().

Context

StackExchange Code Review Q#13305, answer score: 18

Revisions (0)

No revisions yet.