Created
May 30, 2019 01:25
-
-
Save aplocher/288c35a56e817ada5b8a3e4df4eba482 to your computer and use it in GitHub Desktop.
A simple C# function (and console app) to flatten an array down to a specified generic type
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.Generic; | |
namespace ConsoleApp3 | |
{ | |
// This is a sample Console App written in C# / .NET Core (but should work with .NET Framework). | |
// This will flatten an array structure, recursively, down to the generic type specified (or throw an exception if the input is bad) | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
Console.WriteLine("Hello World!"); | |
var a = new object[] | |
{ | |
1, | |
2, | |
new object[] | |
{ | |
3, | |
new int[] | |
{ | |
4, | |
5 | |
} | |
}, | |
6 | |
}; | |
var flatA = Flatten<int>(a); | |
foreach (var item in flatA) | |
{ | |
Console.WriteLine(item); | |
} | |
Console.ReadKey(); | |
// OUTPUT: | |
//Hello World! | |
//1 | |
//2 | |
//3 | |
//4 | |
//5 | |
//6 | |
} | |
public static IEnumerable<T> Flatten<T>(Array input) | |
{ | |
foreach (var item in input) | |
{ | |
if (item is Array) | |
foreach (var flatItem in Flatten<T>((Array)item)) | |
yield return flatItem; | |
else | |
yield return (T)item; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment