【问题标题】:How to Sort a List in Desending Order by the "Value" and Sort the Duplicates by the "Key"?如何按“值”按降序对列表进行排序,并按“键”对重复项进行排序?
【发布时间】:2011-03-15 05:31:40
【问题描述】:

我查看了整个 Internet 以尝试找到如何解决以下问题的示例。

如何按“值”对列表进行降序排序,并按“键”对重复项进行排序? 然后按以下格式打印结果。

我已经附上了我的代码并且它可以工作,但是当您使用 SortedList() 时会出现重复值时会出现问题。如果有人可以修改此代码或确切告诉我如何以另一种方式执行此操作,我将不胜感激,这同样快速有效。

非常感谢您。

排序前:

VALUE's, KEY's

sL.Add(1269.63,"white");
sL.Add(1270.36,"orange");
sL.Add(1272.06,"yellow");
sL.Add(1271.50,"cyan");
sL.Add(1272.06,"black");
sL.Add(1274.12,"dodBlue");
sL.Add(1276.02,"blue");
sL.Add(1273.21,"green");
sL.Add(1275.52,"red");

排序后:

VALUE's, KEY's

sL.Add(1276.02,"blue");
sL.Add(1275.52,"red");
sL.Add(1274.12,"dodBlue");
sL.Add(1273.21,"green");
sL.Add(1272.06,"black");
sL.Add(1272.06,"yellow");
sL.Add(1271.50,"cyan");
sL.Add(1270.36,"orange");
sL.Add(1269.63,"white");

代码:

SortedList sL = new SortedList();

sL.Add(SMA(8)[0], "white");
sL.Add(SMA(10)[0], "orange");
sL.Add(SMA(13)[0], "yellow");
sL.Add(SMA(20)[0], "cyan");
sL.Add(SMA(30)[0], "black");
sL.Add(SMA(40)[0], "dodBlue");
sL.Add(SMA(50)[0], "blue");
sL.Add(SMA(100)[0], "green");
sL.Add(SMA(200)[0], "red");

Print("  " + " " + sL.GetByIndex(8) + " " + ">=" + " " + sL.GetByIndex(7));
Print("&&" + " " + sL.GetByIndex(7) + " " + ">=" + " " + sL.GetByIndex(6));
Print("&&" + " " + sL.GetByIndex(6) + " " + ">=" + " " + sL.GetByIndex(5));
Print("&&" + " " + sL.GetByIndex(5) + " " + ">=" + " " + sL.GetByIndex(4));
Print("&&" + " " + sL.GetByIndex(4) + " " + ">=" + " " + sL.GetByIndex(3));
Print("&&" + " " + sL.GetByIndex(3) + " " + ">=" + " " + sL.GetByIndex(2));
Print("&&" + " " + sL.GetByIndex(2) + " " + ">=" + " " + sL.GetByIndex(1));
Print("&&" + " " + sL.GetByIndex(1) + " " + ">=" + " " + sL.GetByIndex(0));

打印结果:

蓝色 >= 红色;

&& 红色 >= dodBlue ;

&& dodBlue >= 绿色;

&& 绿色 >= 黄色;

&& 黄色 >= 黑色 ;

&& 黑色 >= 青色 ;

&& 青色 >= 橙色;

&& 橙色 >= 白色 ;

【问题讨论】:

    标签: c#


    【解决方案1】:

    为什么不为此使用 LINQ? OrderBy() 和 Distinct() 方法将为您提供帮助。

    【讨论】:

      【解决方案2】:

      您可以使用 LINQ 执行此操作,如下所示:

              Dictionary<int, string> lst = new Dictionary<int,string>(10);
      
              lst.Add(7, "MAX");
              lst.Add(2, "A");
              lst.Add(1, "A");
              lst.Add(8, "0");
      
              Dictionary<int, string> newList = (lst.OrderBy(x => x.Value).ThenBy(x => x.Key)).ToDictionary(x => x.Key,x=>x.Value);
      

      【讨论】:

        猜你喜欢
        • 2021-10-12
        • 1970-01-01
        • 2021-12-20
        • 2022-01-06
        • 1970-01-01
        • 2016-04-08
        • 1970-01-01
        • 2011-11-05
        • 1970-01-01
        相关资源
        最近更新 更多