Skip to content

Instantly share code, notes, and snippets.

@Manuel-S
Last active May 31, 2016 11:42
Show Gist options
  • Select an option

  • Save Manuel-S/c48b4bc5da11e795aab008a4ca00605c to your computer and use it in GitHub Desktop.

Select an option

Save Manuel-S/c48b4bc5da11e795aab008a4ca00605c to your computer and use it in GitHub Desktop.
Flattens an arbitrarily nested array
using System;
using System.Collections;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
//nested array source
var source = new object[]{new object[]{1, 2, new[]{3}}, 4};
//flattened
var flat = source.Flatten<int>();
//display result
Console.WriteLine(string.Join(", ", flat));
}
}
public static class ArrayExtension
{
// flattens the source nested IEnumerable
// returns an IEnumerable of type T
// throws an exception if the source and sub-arrays contain anything but T objects
public static IEnumerable<T> Flatten<T>(this IEnumerable source)
{
foreach(var obj in source)
{
var childCollection = obj as IEnumerable;
if(childCollection != null)
{
foreach(var child in childCollection.Flatten<T>())
{
yield return (T)child;
}
}
else
{
yield return (T)obj;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment