C#排序,无法将Lambda表达式转换为System.Array [英] C# Sort, cannot convert lambda expression to System.Array
问题描述
根据我在.Sort()上找到的内容,这应该可以工作
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);
}
}
但是,我收到此错误消息:
error CS1660: Cannot convert `lambda expression' to non-delegate type `System.Array'
这是我发现该错误的最简单版本.就我而言,我正在使用一个字符串,为它提供一个复杂的排名值,然后进行比较.
我在这里想念什么?
排序过载,您期望
另外,对于数组,Sort
方法是static
,因此您使用类名而不是实例来调用它:
Array.Sort(test, (left, right) => left.CompareTo(right));
CompareTo
是IComparable
类型(如int
)的内置函数,它以上述方式返回int
,因此便于进行排序. /p>
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.
这篇关于C#排序,无法将Lambda表达式转换为System.Array的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!