IComparer using Lambda Expression

Posted by josephj1989 on Stack Overflow See other posts from Stack Overflow or by josephj1989
Published on 2010-05-23T19:46:26Z Indexed on 2010/05/23 19:50 UTC
Read the original article Hit count: 685

Filed under:
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 a parameter. And it works with the lambda as shown in Line 2. But when I try to do as in Line 1, I get an 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.

© Stack Overflow or respective owner

Related posts about c#3.0