Skip to content

Instantly share code, notes, and snippets.

@aplocher
Created May 30, 2019
Embed
What would you like to do?
A simple C# function (and console app) to flatten an array down to a specified generic type
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