Skip to content

Instantly share code, notes, and snippets.

@cirocorvino
Last active August 24, 2020 15:27
Show Gist options
  • Save cirocorvino/3b387317be58b2b411b41ca039deed3e to your computer and use it in GitHub Desktop.
Save cirocorvino/3b387317be58b2b411b41ca039deed3e to your computer and use it in GitHub Desktop.
C# nested array of int type flattener
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Script.Serialization;
namespace FlattenArrayExample
{
public static class Program
{
public static void Main()
{
var originalData = "[[1,2,[3]],4]";
//var originalData = "[[],[1,2,[3]],4]";
//var originalData = "[0,[1,2,[3]],4,[[1]],[],6,[8,9],7]";
//var originalData = "[ 1, 2, 3, \"text\" ]";
var deserializedData = new JavaScriptSerializer().DeserializeObject(originalData);
var flattenedArray = ArrayUtils.getFlattenedIntArray(deserializedData);
if (flattenedArray != null)
{
var flattenedArraySerialized = new StringBuilder();
foreach (var el in flattenedArray)
{
flattenedArraySerialized.Append($"{el},");
}
Console.WriteLine($"{originalData} -> [{flattenedArraySerialized}]");
}
Console.ReadLine();
}
}
public static class ArrayUtils
{
public static int[] getFlattenedIntArray(object nestedArray)
{
var flattenedArray = new List<int>();
var nestedArrayType = nestedArray.GetType();
var expectedType = typeof(int);
if (nestedArrayType.IsArray)
{
foreach (var el in nestedArray as object[])
{
foreach (var retIntEl in getFlattenedIntArray(el)) {
flattenedArray.Add(retIntEl);
}
}
}
else if (nestedArrayType == expectedType)
{
flattenedArray.Add((int)nestedArray);
}
else
{
return new int[0];
}
return flattenedArray.ToArray();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment