As we all know, Enumerable.SelectMany
flattens a sequence of sequences into a single sequence. What if we wanted a method that could flatten sequences of sequences of sequences, and so on recursively?
I came up quickly with an implementation using an ICollection<T>
, i.e. eagerly evaluated, but I'm still scratching my head as to how to make a lazily-evaluated one, say, using the yield
keyword.
static List<T> Flatten<T>(IEnumerable list) {
var rv = new List<T>();
InnerFlatten(list, rv);
return rv;
}
static void InnerFlatten<T>(IEnumerable list, ICollection<T> acc) {
foreach (var elem in list) {
var collection = elem as IEnumerable;
if (collection != null) {
InnerFlatten(collection, acc);
}
else {
acc.Add((T)elem);
}
}
}
Any ideas? Examples in any .NET language welcome.