1

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 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

It would be nice if there was a better error message for when you are sorting a System.Array. Thanks so much!
I'd also like to add, you don't have to use CompareTo. Rolling your own works just as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.