2009-11-26 85 views
1

我需要從嵌套字典中獲取數據IN C#。我的解釋是這樣的:如何從C#中的嵌套字典中獲取數據#

static Dictionary<string, Dictionary<ulong, string>> allOffset = 
    new Dictionary<string, Dictionary<ulong, string>>(); 

我需要獲取所有鍵/全字典的值,表示像這樣:提前

string->>ulong, string 

感謝。

回答

1

遍歷外字典,每次迭代嵌套字典的成員,即

(未經測試代碼)

foreach(var key1 in dc.Keys) 
{ 
    Console.WriteLine(key1); 
    var value1 = dc[key1]; 
    foreach(var key2 in value1.Keys) 
    { 
     Console.WriteLine(" {0}, {1}", key2, value1[key2]); 
    } 
} 
0

嘗試:

string s = dict["key"][_float_]; 

爲了得到整個列表,你可以使用嵌套的foreach循環:

 StringBuilder sb=new StringBuilder(); 
     foreach (var v in dict) 
     { 
      sb.Append(v.Key+"=>>"); 
      foreach (var i in v.Value) 
      { 
       sb.Append(i.Key + ", " + i.Value); 
      } 
      sb.Append(Environment.NewLine); 
     } 

     Console.WriteLine(sb); 
0

這個怎麼樣,該方法將通過所有字典項列舉...

public static IEnumerable<KeyValuePair<ulong, string>> GetValues() 
{ 
    foreach (var pair in allOffset.Values) 
    { 
     foreach (var value in pair) 
     { 
      yield return value; 
     } 
    } 
} 
6

一個LINQ答案(讀取所有的三元組):

var qry = from outer in allOffset 
      from inner in outer.Value 
      select new {OuterKey = outer.Key,InnerKey = inner.Key,inner.Value}; 

或(直接得到字符串) :

var qry = from outer in allOffset 
      from inner in outer.Value 
      select outer.Key + "->>" + inner.Key + ", " + inner.Value; 

foreach(string s in qry) { // show them 
    Console.WriteLine(s); 
} 
+0

打敗了我。我試圖用點符號來實現,但我無法弄清楚如何在不改用糖語法的情況下獲得「內部」。 ; P +1,很棒的回答! – jrista 2009-11-26 06:56:34

3

或者一個在線解決方案

allOffset.SelectMany(n => n.Value.Select(o => n.Key+"->>"+o.Key+","+ o.Value)) 
     .ToList() 
     .ForEach(Console.WriteLine);