2012-12-05 166 views
4

我有以下代碼:如何遍歷字典列表?

List<Dictionary<string, string>> allMonthsList = new List<Dictionary<string, string>>(); 
while (getAllMonthsReader.Read()) { 
    Dictionary<string, string> month = new Dictionary<string, string>(); 
    month.Add(getAllMonthsReader["year"].ToString(), 
    getAllMonthsReader["month"].ToString()); 
    allMonthsList.Add(month); 
} 
getAllMonthsReader.Close(); 

現在我通過所有的幾個月的努力循環,像這樣:

foreach (Dictionary<string, string> allMonths in allMonthsList) 

如何訪問的核心價值觀?難道我做錯了什麼?

回答

9
foreach (Dictionary<string, string> allMonths in allMonthsList) 
{ 
    foreach(KeyValuePair<string, string> kvp in allMonths) 
    { 
     string year = kvp.Key; 
     string month = kvp.Value; 
    } 
} 

BTW年通常有超過一個月。看起來你需要在這裏查找,或Dictionary<string, List<string>>存儲所有月份的一年中。

說明通用字典Dictionary<TKey, TValue> implements IEnumerable接口,它返回一個遍歷集合的枚舉器。從MSDN:

對於枚舉的目的,字典中的每個項被視爲 表示值和其 密鑰的KeyValuePair<TKey, TValue>結構。項目返回的順序是未定義的。

C#語言的foreach語句需要集合中每個元素的類型。 由於Dictionary<TKey, TValue>是鍵和值的集合,因此元素類型不是鍵的類型或值的類型。 而是,元素類型是密鑰 類型和值類型的KeyValuePair<TKey, TValue>

+0

如果美國能源部的'allMnths'從何而來? –

+0

雅我知道我需要從它1個月:)但這返回'錯誤'System.Collections.Generic.Dictionary <字符串,字符串>'不包含'密鑰'的定義和沒有擴展方法'密鑰'接受類型'System.Collections.Generic.Dictionary '的第一個參數可能被發現(你是否缺少使用指令或程序集引用?)\t '嘗試使用字符串時。 –

+0

@lazyberezovsky我認爲他說你有一個語法錯誤。 –

3
var months = allMonthsList.SelectMany(x => x.Keys); 

然後,您可以通過IEnumerable<string>迭代,請你這是所有密鑰的簡單枚舉。

+0

或者,如果你想通過'KeyValuePair'直接迭代,你可以執行'allMonthsList.SelectMany(x => x)' –

1

您的設計是錯誤的。在字典中使用一對是沒有意義的。你不需要使用字典列表。

試試這個:

class YearMonth 
{ 
    public string Year { get; set; } 
    public string Month { get; set; } 
} 

List<YearMonth> allMonths = List<YearMonth>(); 
while (getAllMonthsReader.Read()) 
{ 
    allMonths.Add(new List<YearMonth> { 
          Year = getAllMonthsReader["year"].ToString(), 
          Month = getAllMonthsReader["month"].ToString() 
             }); 
} 

getAllMonthsReader.Close(); 

用途爲:

foreach (var yearMonth in allMonths) 
{ 
    Console.WriteLine("Year is {0}, Month is {1}", yearMonth.Year, yearMonth.Month); 
} 

,或者,如果你使用的.Net框架4.0或以上,你可以使用元組

List<Tuple<string, string>> allMonths = List<Tuple<string, string>>(); 
while (getAllMonthsReader.Read()) 
{ 
    allMonths.Add(Tuple.Create(getAllMonthsReader["year"].ToString(), 
           getAllMonthsReader["month"].ToString()) 
       ); 
} 

getAllMonthsReader.Close ();

然後使用:

foreach (var yearMonth in allMonths) 
{ 
    Console.WriteLine("Year is {0}, Month is {1}", yearMonth.Item1, yearMonth.Item2); 
} 
+1

這不一定是毫無意義的 - 如果直到運行時才知道字段的數量?所有的建議都需要編譯時的知識(如果月份列表只是簡單的1月 - 12月就可以工作,但如果是從輸入讀入其他數據的重複月份列表則不適用)。 –