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.
The SelectMany() method is used to "flatten" a sequence in which each of the elements of the sequence is a separate, subordinate sequence.
Answer: A recursive function is a function that calls itself. A function that calls another function is normal but when a function calls itself then that is a recursive function.
What is Linq SelectMany? The SelectMany in LINQ is used to project each element of a sequence to an IEnumerable<T> and then flatten the resulting sequences into one sequence. That means the SelectMany operator combines the records from a sequence of results and then converts it into one result.
As far as I understood your idea, this is my variant:
static IEnumerable<T> Flatten<T>(IEnumerable collection)
{
foreach (var o in collection)
{
if (o is IEnumerable && !(o is T))
{
foreach (T t in Flatten<T>((IEnumerable)o))
yield return t;
}
else
yield return (T)o;
}
}
and check it
List<object> s = new List<object>
{
"1",
new string[] {"2","3"},
"4",
new object[] {new string[] {"5","6"},new string[] {"7","8"},},
};
var fs = Flatten<string>(s);
foreach (string str in fs)
Console.WriteLine(str);
Console.ReadLine();
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With