Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IComparer using Lambda Expression

Tags:

c#-3.0

 class p {
     public string Name { get; set; }
     public int Age { get; set; }
 };

 static List<p> ll = new List<p>
 {
     new p{Name="Jabc",Age=53},new p{Name="Mdef",Age=20},
     new p{Name="Exab",Age=45},new p{Name="G123",Age=19}
 };
 protected static void SortList()
 {
     IComparer<p> mycomp = (x, y) => x.Name.CompareTo(y.Name);  <==(Line 1)
     ll.Sort((x, y) => x.Name.CompareTo(y.Name));<==(Line 2)
 }

Here the List.sort expects an IComparer<p> as parameter. And it works with the lambda as shown in Line 2. But when I try to do as in Line 1, I get this error:

Cannot convert lambda expression to type System.Collections.Generic.IComparer' because it is not a delegate type

I investigated this for quite some time but I still don't understand it.Maybe my understanding of IComparer is not quite good.Can somebody give me a hand ?

like image 235
josephj1989 Avatar asked May 23 '10 19:05

josephj1989


2 Answers

When you do ll.Sort((x, y) => x.Name.CompareTo(y.Name)); it uses the overload for Comparison<T>, not IComparer. Comparison<T> is a delegate, so you can use a lambda expression for it.

Comparison<p> mycomp = (x, y) => x.Name.CompareTo(y.Name); will work.

like image 165
sepp2k Avatar answered Oct 22 '22 07:10

sepp2k


There's an existing solution you might refer to: https://stackoverflow.com/a/16839559/371531

This one uses Comparer<T>.Create introduced in .NET Framework 4.5.

like image 8
Liu Yue Avatar answered Oct 22 '22 08:10

Liu Yue