【问题标题】:How to sort a list of keyvaluepairs with some operations involved如何对涉及一些操作的键值对列表进行排序
【发布时间】:2021-10-25 17:48:05
【问题描述】:

尽管堆栈溢出中有类似的问题,但我的解决方案无法解决这个问题。我有一个给定的号码,

例如:int target = 15

然后是键值对列表,

var farm = new List<KeyValuePair<string,int>>()
{
   new KeyValuePair<string,int>("apple", 25),
   new KeyValuePair<string,int>("veges", 35),
   new KeyValuePair<string,int>("watermelon", 0),
   new KeyValuePair<string,int>("grapes", 10),
}

现在我想根据给定数字 15 和对列表中的第二个元素的差异对列表进行排序。

到目前为止,这是我的解决方案,但没有做任何更改:

farm.Sort((prod1, prod2) => Math.Abs(prod1.Value - target) < Math.Abs(prod2 - target) 
                                   ? prod1.Value : prod2.Value)

预期的排序应该是:

("grapes", 10)      // |10-15| = 5
("apple", 25)       // |25-15| = 10
("watermelon", 0)  // |0-15| = 15
("veges", 35)       // |35-15| = 20

非常感谢任何见解。

【问题讨论】:

  • 显示预期的输出。另请注意“它不起作用”不是对问题的技术描述,我们无法读懂您的想法
  • @TheGeneral 对不起。

标签: c# list algorithm sorting key-value


【解决方案1】:

您正在使用的List&lt;T&gt;.Sort 的重载接受委托Comparison&lt;T&gt;

docs,对于参数xy,返回值表示如下:

Value Meaning
Less than 0 x is less than y
0 x equals y
Greater than 0 x is greater than y

目前您只是返回较小参数的Value 属性,它与上述条件无关。

您也没有考虑prod1prod2 相等的情况。

最简单的解决方案是从另一个中减去一个:

farm.Sort(
    (prod1, prod2) => Math.Abs(prod1.Value - target) - Math.Abs(prod2 - target));

或者您也可以使用 int.CompareTo,它的作用相同:

farm.Sort(
    (prod1, prod2) => Math.Abs(prod1.Value - target)
        .CompareTo(Math.Abs(prod2 - target)));

【讨论】:

    【解决方案2】:

    试试这个方法:

            int target = 15;
            var farm = new List<KeyValuePair<string, int>>()
            {
                new KeyValuePair<string, int>("apple", 25),
                new KeyValuePair<string, int>("veges", 30),
                new KeyValuePair<string, int>("watermelon", 35),
                new KeyValuePair<string, int>("grapes", 10),
            };
            farm.Sort((prod1, prod2) => Math.Abs(prod1.Value - target).CompareTo(Math.Abs(prod2.Value - target)));
    

    【讨论】:

      猜你喜欢
      • 2022-10-25
      • 2016-03-25
      • 2016-11-17
      • 1970-01-01
      • 2019-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多