views:

57

answers:

4

Hello, Please can you advise me on how to query a Dictionary of Dictionaries, and/or a Dictionary of List?

private Dictionary<string, Dictionary<DateTime, double>> masterDict= new Dictionary<string, Dictionary<DateTime, double>>();

Private Dictionary<string, List<DateTime>> masterList= new Dictionary<string, List<DateTime>>();

I know if I do the following, I get a list of the dictionaries contained in masterDict, but I'm not sure how to get at the values of those dictionaries.

 foreach (var kvp in masterDictMethod())
        {
            Console.WriteLine("Key = {0}, Value = {1}",
                kvp.Key, kvp.Value);
        }

Thanks for looking ;)

A: 

Use masterDict.Values

Aliostad
+3  A: 

In you foreach kvp.Value is the inner dictionary of every masterDict entry i.e. Dictionary<DateTime, double>

So, just foreach also over kvp.Value and you will get the inner values.

e.g.

foreach (var kvp1 in masterDictMethod())
{
   Console.WriteLine("Key = {0}, Inner Dict:", kvp1.Key);
   foreach (var kvp2 in kvp1.Value)
   {
      Console.WriteLine("Date = {0}, Double = {1}", kvp2.Key, kvp2.Value);
   }
}
digEmAll
Perfect. Thank you.
Brian
A: 
foreach (var key in masterDict.Keys)
{
    var nestedDict = masterDict[key];
}
Philippe
Would be better to do: `foreach (var kv in masterDict) { /* work with kv.Value - the inner dict. */ }`. This saves the inner lookup (`Dictionary<K,V>` implements `IEnumerable<KeyValuePair<K,V>>`.)
Richard
A: 

This one is:

var masterDictionary = new Dictionary<string, Dictionary<DateTime, double>>(); 

var query =
  from kvp1 in masterDictionary
  from kvp2 in kvp1.Value
  select new {TheString = kvp1.Key, TheDate = kvp2.Key, TheDouble = kvp2.Value };

foreach(var x in query)
{
  Console.WriteLine("{0} {1} {2}", x.TheString, x.TheDate, x.TheDouble);
}

And then the other one is:

var masterList= new Dictionary<string, List<DateTime>>(); 

var query =
  from kvp in masterList
  from val in kvp.Value
  select new {TheString = kvp.Key, TheDate = val);

foreach(var x in query)
{
  Console.WriteLine("{0} {1}", x.TheString, x.TheDate);
}
David B