C# Sort, cannot convert lambda expression to Syste

2020-04-18 06:38发布

问题:

Based on what I've found on .Sort() this should work

using System;
using System.Linq;

public class Test
{
    public static void Main()
    {
        int[] test = new int[] {6, 2, 1, 4, 9, 3, 7};
        test.Sort((a,b) => a<b);
    }
}

However, I'm getting this error message:

error CS1660: Cannot convert `lambda expression' to non-delegate type `System.Array'

That's the simplest version I could find to get that error. In my case, I'm taking a string, giving it a complex ranking value, and comparing that.

What am I missing here?

回答1:

The overload of Sort that you are after expects a delegate that takes in two objects of the type contained within the array, and returns an int. You need to change your expression to return an int, where you return a negative value for items that come before the other, zero when the items are "equal", and a positive value for items that come after the other.

Also, for arrays the Sort method is static, so you call it using the class name, not as an instance:

Array.Sort(test, (left, right) => left.CompareTo(right));

CompareTo is a built-in function on types that are IComparable (like int), and it returns an int in the manner I described above, so it is convenient to use for sorting.



标签: c# lambda