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 anint
, 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 isstatic
, so you call it using the class name, not as an instance:CompareTo
is a built-in function on types that areIComparable
(likeint
), and it returns anint
in the manner I described above, so it is convenient to use for sorting.