如何获得内部词典的价值?

时间:2016-04-05 21:47:50

标签: c#

这是我的字典。

var dic = new Dictionary<string, Dictionary<string, int>>();

我需要在内部字典中获取int的值。

foreach (var country in dic)
{
    output.AppendFormat("{0} (total population: {1})", country.Key, HERE);
}

任何帮助?

2 个答案:

答案 0 :(得分:2)

如果您想要人口总和(“total popuplation”),您可以使用:

   var sum = country.Value.Values.Sum();
   output.AppendFormat("{0} (total population: {1})", country.Key, sum);

这使用LINQ,因此您需要

using System.Linq;

在源文件中。

答案 1 :(得分:1)

尝试在degugger中运行此示例:

        var dic = new Dictionary<string, Dictionary<string, int>>();
        var cities = new Dictionary<string, int>();
        cities.Add("Kiev", 6000000);
        cities.Add("Lviv", 4000000);

        dic.Add("Ukraine", cities);

        var totalPopulationByCountry = dic.ToDictionary(x => x.Key, y => y.Value.Values);
        var sumPopulationByCountry = dic.ToDictionary(x => x.Key, y => y.Value.Values.Sum());

应该是你需要的