Skip to content

Instantly share code, notes, and snippets.

@kggayo
Last active October 12, 2017 05:59
Show Gist options
  • Save kggayo/db5a8f71a3c7cae4c85ac423d6a8f91c to your computer and use it in GitHub Desktop.
Save kggayo/db5a8f71a3c7cae4c85ac423d6a8f91c to your computer and use it in GitHub Desktop.
C#: Flatten an array of arbitrarily nested arrays into a flat array.
/// <summary>
/// This program will flatten an array of arbitrarily nested arrays of integers into a flat array of integers. e.g. [[1,2,[3]],4] -> [1,2,3,4].
/// It will accept type in nested arrays and specify what type to return in a flatten array format.
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
//create an array of arbitrarily nested arrays
object[] nestedArrays = new object[] { 1,2,3,4, new Int32[]{2,3,4,5}, new object[]{ 6,7,8, new object[]{9,10,11}}, "A", "B", "C"};
//Get only int value type
var resultInt = FlattenArray<int>(nestedArrays);
Console.WriteLine("Length: " + resultInt.Length);
Console.WriteLine("Content: " + String.Join(",", resultInt));
//Get only string value type
var resultString = FlattenArray<String>(nestedArrays);
Console.WriteLine("Length: " + resultString.Length);
Console.WriteLine("Content: " + String.Join(",", resultString));
Console.ReadLine();
}
public static T[] FlattenArray<T>(object[] array) where T : IConvertible
{
List<T> arrayResults = new List<T>();
Flatten(array, arrayResults);
return arrayResults.ToArray();
}
public static void Flatten<T>(object[] array, List<T> arrayResults) where T : IConvertible
{
if (array != null && array.Length > 0)
{
for (int i = 0; i < array.Length; i++)
{
if (array[i] is T[])
{
arrayResults.AddRange((T[])array[i]);
}
else if (array[i] is T)
{
arrayResults.Add((T)array[i]);
}
else if (array[i] is Array)
{
Flatten(array[i] as object[], arrayResults);//try to convert to object array - value types wont work if converted
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment