Grouping consecutive identical items: IEnumerable<T> to IEnumerable<IEnumerable<T>>

Posted by Romain Verdier on Stack Overflow See other posts from Stack Overflow or by Romain Verdier
Published on 2010-05-13T15:49:01Z Indexed on 2010/05/13 15:54 UTC
Read the original article Hit count: 488

I've got an interresting problem: Given an IEnumerable<string>, is it possible to yield a sequence of IEnumerable<string> that groups identical adjacent strings in one pass?

Let me explain.

Considering the following IEnumerable<string> (pseudo representation):

{"a","b","b","b","c","c","d"}

How to get an IEnumerable<IEnumerable<string>> that would yield something of the form:

{ // IEnumerable<IEnumerable<string>>
    {"a"},         // IEnumerable<string>
    {"a","b","b"}, // IEnumerable<string>
    {"c","c"},     // IEnumerable<string>
    {"d"}          // IEnumerable<string>
}

The method prototype would be:

public IEnumerable<IEnumerable<string>> Group(IEnumerable<string> items)
{
    // todo
}

Important notes :

  • Only one iteration over the original sequence
  • No intermediary collections allocations (we can assume millions of strings in the original sequence, and millions consecutives identicals strings in each group)
  • Keeping enumerators and defered execution behavior

Is it possible, and how would you write it?

© Stack Overflow or respective owner

Related posts about c#

Related posts about ienumerable