Last active
May 31, 2016 11:42
-
-
Save Manuel-S/c48b4bc5da11e795aab008a4ca00605c to your computer and use it in GitHub Desktop.
Flattens an arbitrarily nested array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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