简体   繁体   中英

C# Sort, cannot convert lambda expression to System.Array

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?

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.

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