views:

162

answers:

2

I need to fetch data from nested Dictionary IN C#. My Dictionary is like this:

static Dictionary<string, Dictionary<ulong, string>> allOffset = 
  new Dictionary<string, Dictionary<ulong, string>>();

I need to fetch all keys/values of the full dictionary, represented like so:

string->>ulong, string

Thanks in advance.

A: 

I am unsure if you want to write the data to the console, or want to transform it into a new object structure.

But in case you just want to print, give this a try:

foreach( var pair in allOffset )
{
  foreach( var innerPair in pair.Value )
  {
    Console.WriteLine("{0}->>{1},{2}", pair.Key, innerPair.Key, innerPair.Value);
  }
}
Yannick M.
+2  A: 

You can use LINQ to do it:

var flatKeysAndValues =
    from outer in allOffset    // Iterates over the outer dictionary
    from inner in outer.Value  // Iterates over each inner dictionary
    select new
               {
                   NewKey = outer.Key + "->>" + inner.Key,
                   NewValue = inner.Value
               };

Example of usage:

foreach (var flatKeysAndValue in flatKeysAndValues)
{
    Console.WriteLine("NewKey: {0} | NewValue: {1}", 
                             flatKeysAndValue.NewKey, flatKeysAndValue.NewValue);
}
Elisha