开发者

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开发者_Python百科 of the full dictionary, represented like so:

string->>ulong, string

Thanks in advance.


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


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


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜