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

Implementation of GroupBy<TKey, TElement> in .NET

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

Problem

I've implemented the GroupBy extension method for IEnumerable type as an excersise to deep a little more into LINQ.

What do you think about the source code?

Code:

static IEnumerable> GroupBy(this IEnumerable source, Func keySelector)
{
    //Grouping elements in the dictionary according to the criteria
    var dict = new Dictionary>();

    //Filling the dictionary. It will contain: [Key -> List]
    foreach (var x in source)
    {
        var key = keySelector(x);
        if (dict.Keys.Contains(key))
        {
            dict[key].Add(x);
        }
        else
        {
            dict.Add(key, new List { x });
        }
    }

    //For each group...
    foreach (var x in dict)
    {
        yield return new Grouping(x.Key, x.Value);
    }
}

class Grouping : IGrouping
{
    private TKey _key;
    private IEnumerable _elements;

    public Grouping(TKey key, IEnumerable elements)
    {
        _key = key;
        _elements = elements;
    }

    public IEnumerator GetEnumerator()
    {
        return _elements.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    public TKey Key
    {
        get { return _key; }
    }
}

Solution

If you want to duplicate GroupBy semantics exactly, there are several things missing:

  • Eager error checking on parameters instead of deferred



  • The correct order of the groups (GroupBy guarantees that the groups are ordered by the relative order of the group's first element in the source)



  • Allowing keys that are null



You may be interested in Jon Skeet's recent blog postings.

Context

StackExchange Code Review Q#732, answer score: 5

Revisions (0)

No revisions yet.