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.
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 ).
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.
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.
Creating a Nested Dictionary In Python, a Nested dictionary can be created by placing the comma-separated dictionaries enclosed within braces.
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);
}
Or One line solution
allOffset.SelectMany(n => n.Value.Select(o => n.Key+"->>"+o.Key+","+ o.Value))
.ToList()
.ForEach(Console.WriteLine);
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