how to fetch data from nested Dictionary in c#

前端 未结 5 1049
一向
一向 2020-12-19 14:09

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

static Dictionary&         


        
相关标签:
5条回答
  • 2020-12-19 14:31

    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]);
        }
    }
    
    0 讨论(0)
  • 2020-12-19 14:33

    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 讨论(0)
  • 2020-12-19 14:35

    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);
    }
    
    0 讨论(0)
  • 2020-12-19 14:40

    Or One line solution

    allOffset.SelectMany(n => n.Value.Select(o => n.Key+"->>"+o.Key+","+ o.Value))
             .ToList()
             .ForEach(Console.WriteLine);
    
    0 讨论(0)
  • 2020-12-19 14:44

    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;
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题