Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flatten Ruby method in C#

Tags:

arrays

c#

ruby

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
like image 291
chrisntr Avatar asked Oct 13 '08 09:10

chrisntr


1 Answers

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()) { ... }
like image 152
Alexander Kojevnikov Avatar answered Sep 28 '22 08:09

Alexander Kojevnikov