【问题标题】:How to Sort Nested Dictionaries .net C#?如何对嵌套字典 .net C# 进行排序?
【发布时间】:2016-01-17 03:38:00
【问题描述】:
using System;
using System.Collections.Generic;
using System.Linq;

class Dictionary
{
    static void Main()
    {
        Dictionary<string,Dictionary<string,float>> dict = new Dictionary<string, Dictionary<string, float>>();
        String input = Console.ReadLine();
        String[] data = input.Split();
        string name = "";
        float result = 0;

        while (data[0] != "end")
        {
            if (data.Length == 1)
            {
                name = data[0];
                dict.Add(name, new Dictionary<string, float>());
            }
            else if (data.Length > 1)
            {
                result = float.Parse(data[1]);
                dict[name].Add(data[0], result);
            }

            data = Console.ReadLine().Split(); // input 
        }

        // var dic2 = from x in dict
        // orderby x.Key
        // select x; 

        foreach (var item in dict)
        {
            Console.WriteLine("Country: {0}", item.Key);
            string temp = item.Key;

            foreach (var element in dict[temp])
            {
                Console.WriteLine("City: {0}, population: {1}", element.Key, element.Value);
            }
        }
    }
}

我有一个字典键->国家,嵌套->字典键->城市,值->我想要的人口
在内部“嵌套”字典中对国家和人口进行排序。一世 花了几个小时寻找正确的答案,但找不到 解决我的问题。我能够获取信息,但找不到对其进行排序的方法。任何帮助表示赞赏。 PS:我现在只是在学习字典。 谢谢。

【问题讨论】:

  • 您能否举例说明您期望生成的排序字典的结构?

标签: c# .net sorting dictionary nested


【解决方案1】:

您可以使用SortedDictionary 作为您的内部字典。

【讨论】:

    【解决方案2】:

    我假设你有类似的东西(数字)

    USA
    - LA : 5000000
    - New York : 10000000
    - Boston : 3000000
    Australia
    - Sydney : 4000000
    - Canberra : 500000
    Canada
    - Ontario : 1000000
    - Toronto : 2000000
    

    你希望它成为

    Australia
    - Canberra : 500000
    - Sydney : 4000000
    Canada
    - Ontario : 1000000
    - Toronto : 2000000
    USA
    - Boston : 3000000
    - LA : 5000000
    - New York : 10000000
    

    首先,您不能对字典进行排序。但你确实有一些选择。 You can use a SortedDictionary where you specify the comparer。 或者您可以将元素输出到KeyValuePairs 列表并对其进行排序。

    【讨论】:

    • 是的,我想完全按照您在上面的示例中所做的操作。如果它是一个带有键和值的字典,我可以用 linq 对其进行排序,我的意思是将元素排序到另一个 KeyValuePair 集合 // var dic2 = from x in dict // orderby x.Key // select x;但使用嵌套字典它没有工作。
    • 好吧,正如我所说,你有两个选择:
    • 如果您希望元素始终排序,您可以将dict 更改为SortedDictionary&lt;string,SortedDictionary&lt;string,float&gt;&gt;。或者,如果您只想在给定时间对输出的元素进行排序,您可以执行var sorted = dict.ToList().OrderBy(x=&gt;x.Key).Select(country =&gt; new KeyValuePair&lt;string,List&lt;KeyValuePair&lt;string,float&gt;&gt;&gt;(country.Key, country.Value.ToList().OrderBy(x=&gt;x.Value)) 之类的操作,该代码不在我的脑海中,所以可能有错误,但您明白了
    猜你喜欢
    • 2020-04-29
    • 2018-11-23
    • 1970-01-01
    • 2023-03-14
    • 2015-03-31
    • 1970-01-01
    • 2020-11-11
    • 1970-01-01
    • 2021-05-31
    相关资源
    最近更新 更多