【问题标题】:C# Sort, cannot convert lambda expression to System.ArrayC# 排序,无法将 lambda 表达式转换为 System.Array
【发布时间】:2016-04-19 06:14:48
【问题描述】:

根据我在 .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'

这是我能找到的最简单的版本来解决这个错误。在我的例子中,我使用一个字符串,给它一个复杂的排名值,然后进行比较。

我在这里错过了什么?

【问题讨论】:

    标签: c# lambda


    【解决方案1】:

    您所追求的overload of Sort 需要delegate that takes in two objects of the type contained within the array, and returns an int。您需要更改您的表达式以返回 int,其中您为在另一个之前的项目返回负值,当项目“相等”时返回零,为在另一个之后的项目返回正值。

    另外,对于数组,Sort 方法是static,因此您可以使用类名而不是实例来调用它:

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

    CompareToIComparable 类型的内置函数(如int),它以我上面描述的方式返回int,因此使用它进行排序很方便。

    【讨论】:

    • 如果在对 System.Array 进行排序时有更好的错误消息,那就太好了。非常感谢!
    • 我也想补充一下,你不必使用CompareTo。也可以滚动自己的作品。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-07
    • 1970-01-01
    • 1970-01-01
    • 2012-01-15
    相关资源
    最近更新 更多