我正在使用无法序列化嵌套列表的游戏引擎,如List<List<int>>
。我需要的是一个快速解决方案,将多个列表存储在一个列表中。我即将自己写这个,但我想知道是否有任何解决方案已经存在。将嵌套列表与逻辑组合
是否有任何包装可以将'虚拟'嵌套列表存储到一个大列表中,同时提供您期望从单独列表中获得的功能?
我正在使用无法序列化嵌套列表的游戏引擎,如List<List<int>>
。我需要的是一个快速解决方案,将多个列表存储在一个列表中。我即将自己写这个,但我想知道是否有任何解决方案已经存在。将嵌套列表与逻辑组合
是否有任何包装可以将'虚拟'嵌套列表存储到一个大列表中,同时提供您期望从单独列表中获得的功能?
您可以使用Enumerable.SelectMany
扁平化嵌套列表:
List<int> flattened = allLists.SelectMany(l => l).ToList();
有没有可能到unflatten扁平列表返回到嵌套 列表?
你可以使用一个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();
是否可以将拼合列表解开为嵌套列表? – Abdulla 2012-07-24 18:03:25
@Abdulla:编辑我的答案。 – 2012-07-24 18:52:05
你能澄清,如果你是后:
一种扁平化和解除嵌套列表的方法。 – Abdulla 2012-07-24 18:05:16
如何像这样一个办法:
为了展平的列表,使用像其他人所说,使元组的扁平列表(注意,下面所有的代码是未经测试):
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]);
,并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;
}
如果不能序列嵌套列表,这表明它使用了一个非标准的序列化器...所以,假设情况是这样的,它可以序列化什么? – 2012-07-24 17:57:26
它可以序列化标准(非嵌套)列表。 – Abdulla 2012-07-24 18:00:10
任何原因你必须使用该序列化程序,而不是标准的? – 2012-07-24 18:05:59