将嵌套列表与逻辑结合使用

我正在使用无法序列化嵌套列表的游戏引擎,例如List<List> 。 我需要的是一个快速的解决方案,将多个列表存储在一个列表中。 我即将自己写这个,但我想知道是否已经存在任何解决方案。

是否有任何包装器可以将“虚拟”嵌套列表存储到一个大列表中,同时提供您期望从单独列表中获得的function?

您可以使用Enumerable.SelectMany来展平嵌套列表:

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

是否可以将扁平列表展开回嵌套列表?

您可以使用Tuple来存储Item1原始列表的编号以及Item2的编号本身。

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

这样的事情怎么样:

要展平列表,请使用其他人建议制作扁平的元组列表(注意,下面的所有代码都是未经测试的):

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

并且不平坦:

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

你能澄清你是否在追求:

  1. 可以表示嵌套列表的序列化库(例如JSON.NET应该能够)。
  2. 一种压扁列表的方法