Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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?

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)?

like image 210
user673679 Avatar asked Nov 27 '12 22:11

user673679


People also ask

How do you sort a list with lambda function?

The list. sort() method key parameter is set to lambda. The arguement x is the iterable element ( tuple ) to be sorted by the second element, the number. The lambda expression sorts the list by the second element of the tuple value and updates the original.

How do you sort a list of objects based on an attribute of the objects in Java 8?

Java 8 introduced a sort method in the List interface which can use a comparator. The Comparator. comparing() method accepts a method reference which serves as the basis of the comparison. So we pass User::getCreatedOn to sort by the createdOn field.


2 Answers

You can use the Comparer.Create method, although this appears to be new in .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)));
like image 111
Lee Avatar answered Oct 06 '22 16:10

Lee


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

class IntComparer : IComparer<int>
{
    public int Compare(int x, int y)
    {
        return x.CompareTo(y);
    }
}
list.Sort(1, 2, new IntComparer());
like image 27
Tim Schmelter Avatar answered Oct 06 '22 15:10

Tim Schmelter