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

Abd*_*lla 3 c# nested list wrapper

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

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

Tim*_*ter 7

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

List<int> flattened = allLists.SelectMany(l => l).ToList();
Run Code Online (Sandbox Code Playgroud)

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

您可以使用a Tuple<int, int>来存储原始列表Item1的编号和编号本身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();
Run Code Online (Sandbox Code Playgroud)