Combine Nested Lists With Logic

六眼飞鱼酱① 提交于 2019-12-23 18:02:57

问题


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?


回答1:


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();



回答2:


How about something like this:

To flatten a list, use something like others have suggested to make a flattened list of Tuples (note, all code below is untested):

List<List<int>> myStartingList = new List<List<int>>();
List<Tuple<int, int, int>> myFlatList = new List<Tuple<int, int, int>>();
for (var iOuter = 0; iOuter < myStartingList.Count; iOuter++)
    for (var iInner = 0; iInner < myStartingList[iOuter].Count; iInner++)
        myFlatList.Add(new Tuple<int, int, int>(iOuter, iInner, myStartingList[iOuter][iInner]);

and to unflatten:

List<List<int>> myNestedList = new List<List<int>>();
int iOuter=-1;
foreach (var t in myFlattenedList)
{
    if (iOuter != t.Item1)
        myNestedList.Add(new List<Int>());
    iOuter = t.Item1;
    myNestedList[t.Item1][t.Item2] = t.Item3;
}



回答3:


Can you clarify if you are after:

  1. A serialization library that can represent nested lists (e.g. JSON.NET should be able to).
  2. A way to flatten lists


来源:https://stackoverflow.com/questions/11636560/combine-nested-lists-with-logic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!