Flatten an array of objects that may contain arrays

arrays, c#, linq

Solution

IEnumerable<object> source = new object[] { "test", 1, new[] { 1, 2, 3 }, "test" };

var result = source .SelectMany(x => x is Array ? ((IEnumerable)x).Cast<object>() : Enumerable.Repeat(x, 1));

To get it work with nested arrays make the lambda recursive:

IEnumerable<object> source = new object[] { "test", 1, new object[] { 1, 2, new [] { "nested", "nested2" } }, "test" };

Func<IEnumerable<object>, IEnumerable<object>> flatten = null;
flatten = s => s.SelectMany(x => x is Array ? flatten(((IEnumerable)x).Cast<object>()) : Enumerable.Repeat(x, 1));

var result = flatten(source);

Problem

I have an `IEnumerable<object>` which may or may not contain some nested collections. For example, my starting point might look something like this: ``` [ "foo", 2, [1, 2, 3, 4], "bar" ] ``` And I want to flatten it to: ``` [ "foo", 2, 1, 2, 3, 4, "bar" ] ``` I'm thinking a `SelectMany` should work here but can't quite find the right combination. I could brute force it, but I thought there should be a more elegant solution.

Original source