2013-09-30 117 views
0

我有Dictionary<Key, IList<Days>> days需要迭代通過foreach循環,所以我可以將其轉換爲Dictionary<Key, IList<string>> days2; 我嘗試使用以下,但編譯器不喜歡它(無法轉換爲元素的類型。如何迭代其值域是c#中的列表的字典?

foreach(KeyValuePair<string,IList<Days>> kvp in days) 
{ 
//do stuff 
} 

你如何通過字典鍵值對,其值是列表? 如果可能的話,我儘量避免使用LINQ到的foreach使其更具可讀性

+0

你的可變天數是如何定義的? – helb

+0

您可以使用[ToDictionary()](http://msdn.microsoft.com/zh-cn/library/system.linq.enumerable.todictionary.aspx)方法執行轉換。 –

+0

'Dictionary >'days – DoodleKana

回答

4

您可以使用implicitly typed local variable,而不是精確的指定類型的。它使用var關鍵字進行:

foreach (var kvp in dict) 
{ 

} 

您還可以使用LINQ,從而獲得所需Dictionary<Key, IList<string>>

Dictionary<Key, IList<string>> dict2 = 
    dict.ToDictionary(x => x.Key, 
         x => (IList<String>)x.Value.Select(y => y.ToString()).ToList()); 

更換簡單ToString()調用與Daysstring轉換你想使用。

+0

謝謝,我知道var,但由於某種原因,我沒有考慮在這裏使用它。它像魔術一樣工作。我結束了2 foreach循環,內部迭代每個列表元素,然後將其保存到另一個列表與轉換後的值,然後一旦內部foreach完成我用鑰匙保存並添加到轉換列表。 – DoodleKana

2

你必須定義爲Dictionary<Key, IList<Days>>字典,這意味着你應該在foreach循環匹配類型:

foreach (KeyValuePair<Key, IList<Days>> kvp in days) 
{ 
    foreach (Days day in kvp.Value) 
    { 
     // Convert individual elements 
    } 
} 

你的另一個選項是使用ToDictionary擴展方法來轉換:

days.ToDictionary(d => d.Key, d => Value.Select(d => d.ToString())); 
1
foreach(KeyValuePair<string,IList<Days>> kvp in days) 
{ 
    IList<Days> dayList = kvp.Value; 
    // TODO: convert and insert in new dictionary 
} 
+1

foreach(KeyValuePair > kvp in days)這是我遇到編譯器錯誤的部分。 foreach不喜歡在字典中有列表。使用var雖然工作。 – DoodleKana

+0

你仍然錯過了你的foreach循環中的第二個'>' – helb

+0

雅我的壞是一個錯字。其實我的確在我的原始代碼中有這個,你仍然會遇到編譯錯誤。 – DoodleKana