简体   繁体   English

如何使用 LINQ 按降序对值进行排序,并按字母顺序对键进行排序?

[英]How do I sort Value in descending order and Key in Alphabetical order using LINQ?

This is what I did,这就是我所做的

Dictionary<string, int> colorRank = new Dictionary<string, int>();

//Code to fill the dictionary. //填充字典的代码。

var result = colorRank.OrderByDescending(i => i.Value).ThenBy(i => i.Key);

It's sorting the Value's to Descending order but not sorting Key's in Alphabetical order.它将值按降序排序,但不按字母顺序对键进行排序。 Any Suggestions?有什么建议?

This behavior is expected.这种行为是意料之中的。 You are overwriting your first sort.你正在覆盖你的第一个排序。 You can only notice the difference if you have repeated values in the values, Then the list of the keys for that value will be sorted alphabetically as you expect.如果您在值中有重复的值,您只能注意到差异,然后该值的键列表将按您期望的字母顺序排序。 So your code is correct and so is your expectation.所以你的代码是正确的,你的期望也是如此。 Notice keys for 10 in the below example for your code.请注意以下代码示例中 10 的键。

public static void methodSort()
    {
        Dictionary<string, int> colorRank = new Dictionary<string, int>();
        //Code to fill the dictionary.
        colorRank.Add("bla2", 10);
        colorRank.Add("bla1", 1);
        colorRank.Add("bla3", 11);
        colorRank.Add("blay", 5);
        colorRank.Add("blay1", 10);
        var result = colorRank.OrderByDescending(i => i.Value).ThenBy(i => i.Key);

        foreach (var v in result)
        {
            Console.WriteLine($"{v.Key} {v.Value}");
        }
        /* Output
           bla3 11
           bla2 10
           blay1 10
           blay 5
           bla1 1
         */
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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