简体   繁体   English

具有lambda表达式的List.Sort

[英]List.Sort with lambda expression

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. 猜测是因为没有System.Comparison重载的范围。 Is this omitted for any particular reason? 是否出于任何特定原因而忽略了此?

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>((...) => ...))或者其他的东西)?

You can use the Comparer.Create method, 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)));

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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM