Grouping consecutive identical items: IEnumerable<T> to IEnumerable<IEnumerable<T>>
- by Romain Verdier
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?