Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to fetch data from nested Dictionary in c#

Tags:

c#

dictionary

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.

like image 559
Royson Avatar asked Nov 26 '09 06:11

Royson


People also ask

How to Get value from a nested dictionary?

Access Values using get() Another way to access value(s) in a nested dictionary ( employees ) is to use the dict. get() method. This method returns the value for a specified key. If the specified key does not exist, the get() method returns None (preventing a KeyError ).

What are nested dictionaries?

In Python, a nested dictionary is a dictionary inside a dictionary. It's a collection of dictionaries into one single dictionary. Here, the nested_dict is a nested dictionary with the dictionary dictA and dictB . They are two dictionary each having own key and value.

Is dictionary a collection in C#?

In C#, Dictionary is a generic collection which is generally used to store key/value pairs. The working of Dictionary is quite similar to the non-generic hashtable. The advantage of Dictionary is, it is generic type. Dictionary is defined under System.

Can you Create a dictionary within a dictionary Python?

Creating a Nested Dictionary In Python, a Nested dictionary can be created by placing the comma-separated dictionaries enclosed within braces.


2 Answers

A LINQ answer (that reads all the triples):

var qry = from outer in allOffset
          from inner in outer.Value
          select new {OuterKey = outer.Key,InnerKey = inner.Key,inner.Value};

or (to get the string directly):

var qry = from outer in allOffset
          from inner in outer.Value
          select outer.Key + "->>" + inner.Key + ", " + inner.Value;

foreach(string s in qry) { // show them
    Console.WriteLine(s);
}
like image 180
Marc Gravell Avatar answered Sep 21 '22 15:09

Marc Gravell


Or One line solution

allOffset.SelectMany(n => n.Value.Select(o => n.Key+"->>"+o.Key+","+ o.Value))
         .ToList()
         .ForEach(Console.WriteLine);
like image 31
Ray Lu Avatar answered Sep 21 '22 15:09

Ray Lu