Created
September 3, 2018 10:18
-
-
Save stipebosnjak/17ab654bdad7f6418df6b2d748d62fd5 to your computer and use it in GitHub Desktop.
Flatten an array of arbitrarily nested arrays of objects into a flat array of objects
This file contains 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 FlatNestedArray | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
//[ [1, 2 , [3] ] ,4 ] -> [1,2,3,4] | |
var nestedArrays = new object[] { new object[] { 1, 2, new object[] { 3 } }, 4 }; | |
List<object> flattenedList = new List<object>(); | |
FlattenArray(nestedArrays, ref flattenedList); | |
flattenedList.ForEach(Console.WriteLine); | |
Console.ReadLine(); | |
} | |
/// <summary> | |
/// Recursive function to flatten nested object arrays | |
/// </summary> | |
/// <param name="nestedArray">Nested array to flatten</param> | |
/// <param name="flattenedList">Flattened result list</param> | |
private static void FlattenArray(object [] nestedArray, ref List<object> flattenedList) | |
{ | |
for (int i = 0; i < nestedArray.Length; i++) | |
{ | |
var item = nestedArray[i]; | |
if (item is object[] array) | |
{ | |
FlattenArray(array, ref flattenedList); | |
} | |
else | |
{ | |
flattenedList.Add(item); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment