C# Dictionary 排序

Dictionary<string, int> dicts = new Dictionary<string, int>();
            dicts["ma"] = 123;
            dicts["qing"] = 234;
            dicts["li"] = 12;
            dicts["ping"] = 534;
            dicts["zhang"] = 567;
            dicts["ya"] = 5345;
            
            Console.WriteLine("Exp:\t1");
            foreach (string key in dicts.Keys)
                Console.WriteLine(key + "\t" + dicts[key].ToString());
            Console.WriteLine();


            Console.WriteLine("Exp:\t2");
            var sorted = from entry in dicts orderby entry.Value descending select entry;
            foreach (KeyValuePair<string, int> pair in sorted)
                Console.WriteLine(pair.Key + "\t" + pair.Value.ToString());
            Console.WriteLine();


            Console.WriteLine("Exp:\t3");
            List<KeyValuePair<string, int>> sortedPairs = dicts.OrderByDescending(c => c.Value).ToList();
            foreach(KeyValuePair<string, int> pair in sortedPairs)
                Console.WriteLine(pair.Key + "\t" + pair.Value.ToString());
            Console.WriteLine();



Result:

Exp:    1
ma      123
qing    234
li      12
ping    534
zhang   567
ya      5345

Exp:    2
ya      5345
zhang   567
ping    534
qing    234
ma      123
li      12

Exp:    3
ya      5345
zhang   567
ping    534
qing    234
ma      123
li      12



你可能感兴趣的:(C# Dictionary 排序)