Implementation of GroupBy in .NET I've implemented the GroupBy extension method for IEnumerable&lt;T&gt; type as an excersise to deep a little more into LINQ.

What do you think about the source code?

Code:  

static IEnumerable&lt;IGrouping&lt;TKey,TElement&gt;&gt; GroupBy&lt;TKey,TElement&gt;(this IEnumerable&lt;TElement&gt; source, Func&lt;TElement,TKey&gt; keySelector)
{
    //Grouping elements in the dictionary according to the criteria
    var dict = new Dictionary&lt;TKey, List&lt;TElement&gt;&gt;();

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

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

class Grouping&lt;TKey, TElement&gt; : IGrouping&lt;TKey, TElement&gt;
{
    private TKey _key;
    private IEnumerable&lt;TElement&gt; _elements;

    public Grouping(TKey key, IEnumerable&lt;TElement&gt; elements)
    {
        _key = key;
        _elements = elements;
    }

    public IEnumerator&lt;TElement&gt; GetEnumerator()
    {
        return _elements.GetEnumerator();
    }

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

    public TKey Key
    {
        get { return _key; }
    }
}
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.