Flatten

Flatten a list of nested object which contain data like this:

Input: [1, 2, [3, [4, 5], [6, 7, [8, [9]]]]]

Output: [1,2,3,4,5,6,7,8,9]


public class Program
{
     // var nestedList = new List<object> { 1, 2, new List<object> { 3, new List<object> { 4, 5 }, new List<object> { 6, 7, new List<object> { 8, new List<object> { 9 } } } } };
    public void Flatten(List<object> nestedList, List<int> flatList)
    {
        foreach (var item in nestedList)
        {
            if (item is int)
            {
                flatList.Add((int)item);
            }
            else if (item is List<object>)
            {
                Flatten((List<object>)item, flatList);
            }
        }
    }
}

Last updated