简体   繁体   中英

How to Sort Nested Dictionaries .net C#?

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

I have a Dictionary Key->country,nested->Dictionary Key->city,Value->population where I want to
sort country and population in the inner "nested" dictionary. I spent few hours in search for the right answer but couldn't find the solution to my problem. I am able to foreach the information but can't find the way to sort it. Any help appreciated. PS: I am just learning Dictionaries now. Thanks.

您可以将SortedDictionary用于内部字典。

I'm assuming you have something like (numbers made up)

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

and you want it to be

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

First off, you can't sort a dictionary. But you do have some options. You can use a SortedDictionary where you specify the comparer . Or you can output the elements to a list of KeyValuePairs and sort that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM