2013-07-03 66 views
1

我想用C#中的字典與列表相結合這樣字典和列表

Dictionary<int, List<int>> Dir = new Dictionary<int, List<int>>(); 

,但我有添加鍵和值的語法的麻煩。我想如果我只是做了一些像

Dir.Add(integer1, integer2); 

它會添加integer1是關鍵,整數2作爲值。然後,如果我想添加到整數1鍵,我會做

Dir.Add[interger1].Add(interger3); 

我有一個問題,我有一個foreach循環是這樣顯示的按鍵

foreach (KeyValuePair<int, List<int>> k in labelsList) 
{ 
    Console.WriteLine(k.Key + " "+ k.Value); 
} 

它顯示我的預期的關鍵至多7個,但不顯示該值的我希望它表明,它只是顯示

1 System.Collections.Generic.List`1 [System.Int32]

2 System.Collections.Generic .List`1 [System.Int32]

3 System.Collections.Generic.List`1 [System.Int32]

4 System.Collections.Generic.List`1 [System.Int32]

5系統。 Collections.Generic.List`1 [System.Int32]

6 System.Collections.Generic.List`1 [System.Int32]

7 System.Collections.Generic.List`1 [System.Int32]

我h AVE任何主意,用一個嵌套的foreach像

foreach (KeyValuePair<int, List<int>> k in labelsList) 
{ 
    foreach (KeyValuePair<int, List<int>> k in labelsList) 
    { 
     Console.WriteLine(k.Key + " " + k.Value); 
    } 
} 

但我不確定該怎麼把嵌套的foreach內通過列表

回答

1

當你調用Dir.Add(),你需要一個List<int>對象提供參考。提供一個int本身是不正確的。所以,你需要的東西是這樣的:

Dir.Add(integer1, new List<int>()); 

然後你就可以更新像這樣的條目:

Dir[integer1].Add(integer2); 
Dir[integer1].Add(integer3); 

或者,你可以使用集合初始化語法:

Dir.Add(integer1, new List<int> { integer2, integer3}); 
+0

非常感謝。 –

0

首先迭代,爲您的關鍵integer1一個條目,除非你有已經這樣做了:

Dir.Add(integer1, new List<int>()); 

然後,找到合適的字典項,然後添加到它的價值(在這種情況下,您的列表):

Dir[integer1].Add(integer2); 

在其他答案中可以找到更多完整的代碼片段,如果這是您正在尋找的。

+0

將拋出'NullReferenceException'關鍵時在字典中不存在。 – MarcinJuraszek

+1

@MarcinJuraszek如果鍵不在字典中,它將拋出'KeyNotFoundException'。 –

+0

他要求*語法*。 –

2

您必須先將集合添加到字典中,然後才能開始向其添加值。這是一個查找的解決方案(如果使用ContainsKey,則爲兩個)。它還會添加列表,如果它丟失。

public class YourClass 
{ 
    private Dictionary<int, List<int>> _dictionary = new Dictionary<int, List<int>>(); 

    public void AddItem(int key, int value) 
    { 
     List<int> values; 
     if (!_dictionary.TryGetValue(key, out values)) 
     { 
      values = new List<int>(); 
      _dictionary.Add(key, values); 
     } 

     values.Add(value); 
    } 

    public IEnumerable<int> GetValues(int key) 
    { 
     List<int> values; 
     if (!_dictionary.TryGetValue(key, out values)) 
     { 
      return new int[0]; 
     } 

     return values; 
    } 
} 
+0

'if'條件應該是'if(!_ dictionary.TryGetValue(...))':) – MarcinJuraszek

+0

@MarcinJuraszek你* *已經編輯了:-) –

+0

@Adam Houldsworth:謝謝修復=)我也加了一個GetValues方法。 – jgauffin

0

您需要添加一個List<int>作爲值。它會像這樣工作:

if (!Dir.ContainsKey(integer1)) { 
    Dir.Add(integer1, new List<int>()); 
} 

var list = Dir[integer1]; 
list.Add(integer2); 
+0

不是最有效的,但技術上是正確的。 –

0

如果你想添加一個項目,只需使用此代碼

(而dic是你Dictionary<Int32, List<Int32>>

if (dic.ContainsKey(yourKey)) 
{ 
    dic[yourKey].Add(yourInt); 
} else { 
    dic[yourKey] = new List<int> { yourInt }; 
}