Combine Nested Lists With Logic

c#, list, nested, wrapper

Solution

You can use `Enumerable.SelectMany` to flatten nested lists:

List<int> flattened = allLists.SelectMany(l => l).ToList();

Would it be possible to unflatten a flattened list back into nested lists?

You could use a `Tuple<int, int>` to store the number of the original list in `Item1` and the number itself in `Item2`.

// create sample data
var allLists = new List<List<int>>() { 
    new List<int>(){ 1,2,3 },
    new List<int>(){ 4,5,6 },
    new List<int>(){ 7,8,9 },
};

List<Tuple<int, int>> flattened = allLists
    .Select((l, i) => new{ List = l, Position = i + 1 })
    .SelectMany(x => x.List.Select(i => Tuple.Create(x.Position, i)))
    .ToList();

// now you have all numbers flattened in one list:
foreach (var t in flattened)
{
    Console.WriteLine("Number: " + t.Item2); // prints out the number
}
// unflatten
allLists = flattened.GroupBy(t => t.Item1)
                    .Select(g => g.Select(t => t.Item2).ToList())
                    .ToList();

Problem

I'm using a game engine that cannot serialize nested lists such as `List<List<int>>`. What I need is a quick solution that will store multiple lists into one list. I am about to write this on my own but am wondering if any solutions already exist. Are there any wrappers out there that can store 'virtual' nested lists into one big list while providing the functionality you would expect from separate lists?

Original source