如何从c#中的嵌套字典中获取数据

时间:2009-11-26 06:35:49

标签: c# dictionary

我需要从嵌套字典 IN C#中获取数据。我的词典是这样的:

static Dictionary<string, Dictionary<ulong, string>> allOffset = 
  new Dictionary<string, Dictionary<ulong, string>>();

我需要获取完整字典的所有键/值,如下所示:

string->>ulong, string

提前致谢。

5 个答案:

答案 0 :(得分:7)

LINQ答案(读取所有三元组):

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

或(直接获取字符串):

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

答案 1 :(得分:5)

或一线解决方案

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

答案 2 :(得分:1)

尝试:

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

要获取整个列表,您可以使用嵌套的foreach循环:

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

答案 3 :(得分:1)

迭代外部字典,每次迭代嵌套字典的成员,即

(未经测试的代码)

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

答案 4 :(得分:0)

这个怎么样,该方法将枚举所有字典项...

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