Reputation: 16072
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?
Upvotes: 4
Views: 15750
Reputation: 33391
Your design is wrong. Using one pair in dictionary is meaningless. You don't need to use list of dictionary.
Try this:
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();
Use as:
foreach (var yearMonth in allMonths)
{
Console.WriteLine("Year is {0}, Month is {1}", yearMonth.Year, yearMonth.Month);
}
or, if you use .Net framework 4.0 or above, you can use Tuple
List<Tuple<string, string>> allMonths = List<Tuple<string, string>>();
while (getAllMonthsReader.Read())
{
allMonths.Add(Tuple.Create( getAllMonthsReader["year"].ToString(),
getAllMonthsReader["month"].ToString())
);
}
getAllMonthsReader.Close();
Then use:
foreach (var yearMonth in allMonths)
{
Console.WriteLine("Year is {0}, Month is {1}", yearMonth.Item1, yearMonth.Item2);
}
Upvotes: 1
Reputation: 236308
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.
Upvotes: 15
Reputation: 25234
var months = allMonthsList.SelectMany(x => x.Keys);
You can then iterate through the IEnumerable<string>
as you please which is a simple enumeration of all your keys.
Upvotes: 3