简体   繁体   English

自定义排序功能不起作用

[英]Custom Sort function does not work

I have implemented a custom sort function for a list. 我已经为列表实现了自定义排序功能。 But after calling it, the order of the list does not seem to change. 但是在调用它之后,列表的顺序似乎并没有改变。

I want to find the largest number that comes from the combination of all numbers. 我想找到来自所有数字组合的最大数字。 eg, give 540, 9, it should output 9540 instead of 5409. So The compare function does the job. 例如,给定540、9,它应该输出9540而不是5409。因此,比较功能可以完成此工作。

    public void LargestPossibleNumberCombination(List<int> nums) {
        nums.Sort(CustomCompare);

    }
    public int CustomCompare(int x, int y)
    {
        string a = x +""+ y;
        string b = y + "" + x;
        return a.CompareTo(b) > 0 ? 0 : 1;
    }

You need to return a value when x is less than y (<0), when y is less than x (>0) and when are equals (0). x小于y (<0), y小于x (> 0)和等于(0)时,您需要返回一个值。

However you can make this sort more compact using a lambda comparison: 但是,您可以使用lambda比较使这种排序更为紧凑:

nums.Sort((x, y) => string.Compare(string.Format("{0}{1}", y, x), 
                                   string.Format("{0}{1}", x, y)));

If you want to join the list after being sorted: 如果要在排序后加入列表:

var result = string.Join("", nums);

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

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