2012-07-24 132 views
3

我正在使用無法序列化嵌套列表的遊戲引擎,如List<List<int>>。我需要的是一個快速解決方案,將多個列表存儲在一個列表中。我即將自己寫這個,但我想知道是否有任何解決方案已經存在。將嵌套列表與邏輯組合

是否有任何包裝可以將'虛擬'嵌套列表存儲到一個大列表中,同時提供您期望從單獨列表中獲得的功能?

+1

如果不能序列嵌套列表,這表明它使用了一個非標準的序列化器...所以,假設情況是這樣的,它可以序列化什麼? – 2012-07-24 17:57:26

+0

它可以序列化標準(非嵌套)列表。 – Abdulla 2012-07-24 18:00:10

+0

任何原因你必須使用該序列化程序,而不是標準的? – 2012-07-24 18:05:59

回答

6

您可以使用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(); 
+1

是否可以將拼合列表解開爲嵌套列表? – Abdulla 2012-07-24 18:03:25

+0

@Abdulla:編輯我的答案。 – 2012-07-24 18:52:05

0

你能澄清,如果你是後:

  1. 一個序列化庫,可以代表嵌套的列表(例如JSON.NET應該可以)。
  2. 拉平列表
+0

一種扁平化和解除嵌套列表的方法。 – Abdulla 2012-07-24 18:05:16

1

如何像這樣一個辦法:

爲了展平的列表,使用像其他人所說,使元組的扁平列表(注意,下面所有的代碼是未經測試):

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; 
}