Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate through List of Dictionaries?

I have the following code :

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();

Now I'm trying to loop through all of the months, like this :

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

How do I access the key values? Am I doing something wrong?

like image 697
eric.itzhak Avatar asked Nov 30 '22 22:11

eric.itzhak


1 Answers

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

BTW year usually has more than one month. Looks like you need a lookup here, or Dictionary<string, List<string>> for storing all months of year.

Explanation generic dictionary Dictionary<TKey, TValue> implements IEnumerable interface, which returns an enumerator that iterates through the collection. From msdn:

For purposes of enumeration, each item in the dictionary is treated as a KeyValuePair<TKey, TValue> structure representing a value and its key. The order in which the items are returned is undefined.

The foreach statement of the C# language requires the type of each element in the collection. Since the Dictionary<TKey, TValue> is a collection of keys and values, the element type is not the type of the key or the type of the value. Instead, the element type is a KeyValuePair<TKey, TValue> of the key type and the value type.

like image 172
Sergey Berezovskiy Avatar answered Dec 04 '22 08:12

Sergey Berezovskiy