2012-09-07 36 views
-17

這是一本字典:從字典到列表

Dictionary<string, List<string>> Dic = new Dictionary<string, List<string>>(); 

我要做到以下幾點:當我點擊一個按鈕,第一詞典(DIC)鍵和它的值複製到一個列表(List<string>)。再次點擊,同樣的事情發生,但這次與下一個字典的關鍵和價值。

+0

對不起,我不明白你的問題。你的意思是你想添加一個列表到詞典?或者您在訪問列表時遇到問題? – hydev

+0

詞典中沒有明確的順序。 – mbm

+0

你的[上一個問題](http://stackoverflow.com/q/12312240/961113) – Habib

回答

0

爲什麼不使用ToList方法?

Dictionary<string, int> dictionary = new Dictionary<string, int>(); 
dictionary["cat"] = 1; 
dictionary["dog"] = 4; 
dictionary["mouse"] = 2; 
dictionary["rabbit"] = -1; 

// Call ToList. 
List<KeyValuePair<string, int>> list = dictionary.ToList(); 

// Loop over list. 
foreach (KeyValuePair<string, int> pair in list) 
{ 
    Console.WriteLine(pair.Key); 
    Console.WriteLine(" {0}", pair.Value); 
} 
+0

我有Dictionary > Dic = new Dictionary >(); ----------- ------- no詞典 dictionary =新詞典(); –

1

看起來像你想創建一個基於字典的值列表所有字符串元素的新List<string>。您可以使用SelectMany使用下面的代碼來壓平,並得到一個列表:

Dictionary<string, List<string>> Dic = new Dictionary<string, List<string>>(); 
Dic.Add("1", new List<string>{"ABC","DEF","GHI"}); 
Dic.Add("2", new List<string>{"JKL","MNO","PQR"}); 
Dic.Add("3", new List<string>{"STU","VWX","YZ"}); 

List<string> strList = Dic.SelectMany(r => r.Value).ToList(); 

strList將包含在一個單一的列表從詞典中所有的字符串項。