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?
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 aKeyValuePair<TKey, TValue>
of the key type and the value type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With