C# List.Sort 与 lambda 表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13594475/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:08:04  来源:igfitidea点击:

List.Sort with lambda expression

c#listsortingdelegateslambda

提问by user673679

I'm trying to sort part of a list with a lambda expression, but I get an error when trying to do so:

我正在尝试使用 lambda 表达式对列表的一部分进行排序,但是在尝试这样做时出现错误:

List<int> list = new List<int>();
list.Add(1);
list.Add(3);
list.Add(2);
list.Add(4);

// works fine
list.Sort((i1, i2) => i1.CompareTo(i2) );

// "Cannot convert lambda expression to type 'System.Collections.Generic.IComparer<int>' because it is not a delegate type"
list.Sort(1, 2, (i1, i2) => i1.CompareTo(i2) );

foreach (int i in list)
    Console.WriteLine(i);

At a guess this is because there's no System.Comparison overload for the sort that takes a range. Is this omitted for any particular reason?

猜测这是因为对于采用范围的排序没有 System.Comparison 重载。是否出于任何特殊原因省略了这一点?

Is there an easy way of getting a suitable IComparer from the lambda expression (like a class I can just use to go list.Sort(1, 2, new CompareyThing<int>((...) => ...))or something)?

有没有一种简单的方法可以从 lambda 表达式中获取合适的 IComparer(比如一个我可以用来去的类list.Sort(1, 2, new CompareyThing<int>((...) => ...)))?

采纳答案by Lee

You can use the Comparer.Createmethod, although this appears to be new in .Net 4.5

您可以使用Comparer.Create方法,尽管这在 .Net 4.5 中似乎是新的

list.Sort(1, 2, Comparer<int>.Create((i1, i2) => i1.CompareTo(i2)));

You can always create your own comparer:

您始终可以创建自己的比较器:

public class FuncComparer<T> : IComparer<T>
{
    private readonly Func<T, T, int> func;
    public FuncComparer(Func<T, T, int> comparerFunc)
    {
        this.func = comparerFunc;
    }

    public int Compare(T x, T y)
    {
        return this.func(x, y);
    }
}

Then your code would be:

那么你的代码将是:

list.Sort(1, 2, new FuncComparer<int>((i1, i2) => i1.CompareTo(i2)));

回答by Tim Schmelter

You could create a custom comparer if you're not using .Net 4.5:

如果您不使用 .Net 4.5,您可以创建一个自定义比较器:

class IntComparer : IComparer<int>
{
    public int Compare(int x, int y)
    {
        return x.CompareTo(y);
    }
}
list.Sort(1, 2, new IntComparer());