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 sequen
As far as I understood your idea, this is my variant:
static IEnumerable Flatten(IEnumerable collection)
{
foreach (var o in collection)
{
if (o is IEnumerable && !(o is T))
{
foreach (T t in Flatten((IEnumerable)o))
yield return t;
}
else
yield return (T)o;
}
}
and check it
List
Obviously, it does lack some type validity checks (an InvalidCastExcpetion
if collection contains not T
, and probably some other drawbacks)...well, at least it's lazy-evaluated, as desired.
!(o is T)
was added to prevent flattenning of string
to char
array