How can I do the Ruby method "Flatten" Ruby Method in C#. This method flattens a jagged array into a single-dimensional array.
For example:
s = [ 1, 2, 3 ] #=> [1, 2, 3]
t = [ 4, 5, 6, [7, 8] ] #=> [4, 5, 6, [7, 8]]
a = [ s, t, 9, 10 ] #=> [[1, 2, 3], [4, 5, 6, [7, 8]], 9, 10]
a.flatten #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Recursive solution:
IEnumerable Flatten(IEnumerable array)
{
foreach(var item in array)
{
if(item is IEnumerable)
{
foreach(var subitem in Flatten((IEnumerable)item))
{
yield return subitem;
}
}
else
{
yield return item;
}
}
}
EDIT 1:
Jon explains in the comments why it cannot be a generic method, take a look!
EDIT 2:
Matt suggested making it an extension method. Here you go, just replace the first line with:
public static IEnumerable Flatten(this IEnumerable array)
and you can use it like this:
foreach(var item in myArray.Flatten()) { ... }
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