Royson
Royson

Reputation: 2901

how to fetch data from nested Dictionary in c#

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.

Upvotes: 5

Views: 18833

Answers (5)

Ray Lu
Ray Lu

Reputation: 26658

Or One line solution

allOffset.SelectMany(n => n.Value.Select(o => n.Key+"->>"+o.Key+","+ o.Value))
         .ToList()
         .ForEach(Console.WriteLine);

Upvotes: 6

Marc Gravell
Marc Gravell

Reputation: 1062955

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);
}

Upvotes: 8

Rohan West
Rohan West

Reputation: 9298

What about this, the method will enumerate through all dictionary items...

public static IEnumerable<KeyValuePair<ulong, string>> GetValues()
{
    foreach (var pair in allOffset.Values)
    {
        foreach (var value in pair)
        {
            yield return value;
        }
    }
}

Upvotes: 1

Adam Ralph
Adam Ralph

Reputation: 29956

Iterate over the outer dictionary, each time iterating members of the nested dictionary, i.e.

(Untested code)

foreach(var key1 in dc.Keys)
{
    Console.WriteLine(key1);
    var value1 = dc[key1];
    foreach(var key2 in value1.Keys)
    {
        Console.WriteLine("    {0}, {1}", key2, value1[key2]);
    }
}

Upvotes: 2

TheVillageIdiot
TheVillageIdiot

Reputation: 40507

try:

string s = dict["key"][_float_];

For getting whole lists you can use nested foreach loops:

        StringBuilder sb=new StringBuilder();
        foreach (var v in dict)
        {
            sb.Append(v.Key+"=>>");
            foreach (var i in v.Value)
            {
                sb.Append(i.Key + ", " + i.Value);
            }
            sb.Append(Environment.NewLine);
        }

        Console.WriteLine(sb);

Upvotes: 0

Related Questions