简体   繁体   中英

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.

    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).

However you can make this sort more compact using a lambda comparison:

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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