将嵌套列表与逻辑结合 [英] Combine Nested Lists With Logic

查看:102
本文介绍了将嵌套列表与逻辑结合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的游戏引擎无法序列化List<List<int>>之类的嵌套列表.我需要的是一种快速解决方案,它将多个列表存储到一个列表中.我将自己写这篇文章,但想知道是否已经存在解决方案.

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?

推荐答案

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

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?

您可以使用Tuple<int, int>Item1中存储原始列表的编号,并在Item2中存储编号本身.

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

这篇关于将嵌套列表与逻辑结合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆