public static IEnumerable <IGrouping <TKey, TSource> > GroupBy <TSource, TKey>(this IAdjacentGroupingSource <TSource> source, Func <TSource, TKey> keySelector, IEqualityComparer <TKey> comparer = null) { if (source == null) { throw new ArgumentNullException("source"); } if (keySelector == null) { throw new ArgumentNullException("keySelector"); } return(AdjacentGroupingEnumerable(source, keySelector, comparer)); }
private static IEnumerable <IGrouping <TKey, TSource> > AdjacentGroupingEnumerable <TSource, TKey>(IAdjacentGroupingSource <TSource> source, Func <TSource, TKey> keySelector, IEqualityComparer <TKey> comparer) { if (comparer == null) { comparer = EqualityComparer <TKey> .Default; } using (var en = source.GetEnumerator()) { if (en.MoveNext()) { var currentGroup = new Grouping <TKey, TSource>(keySelector(en.Current)); currentGroup.Elements.Add(en.Current); while (en.MoveNext()) { //Test whether current element starts a new group TKey newKey = keySelector(en.Current); if (!comparer.Equals(newKey, currentGroup.Key)) { //Yield the previous group and start next one yield return(currentGroup); currentGroup = new Grouping <TKey, TSource>(newKey); } //Add element to the current group currentGroup.Elements.Add(en.Current); } //Yield the last group of sequence yield return(currentGroup); } } }