0
var pairs = new [] { new { id = 1, name = "ram", dept = "IT", sal = "3000" }, new { id = 2, name = "ramesh", dept = "IT", sal = "5000" }, new { id = 3, name = "rahesh", dept = "NONIT", sal = "2000" },
                             new { id = 5, name = "rash", dept = "NONIT", sal = "7000" } };
        var query = from stud in pairs
                    where (stud.name.StartsWith("r") && stud.id % 2 != 0)
                    //orderby stud.sal descending
                    group stud by stud.dept into grps
                    select new { Values = grps, Key = grps.Key, maxsal=grps.Max() };
                    ////select new { id = stud.id };

        foreach (dynamic result in query)
        {
            Console.WriteLine(result.Key);
            Console.WriteLine(result.maxsal);
            foreach (dynamic result2 in result.Values)
            {
                Console.WriteLine(result2.id + "," + result2.sal);
            }


        }
        Console.Read();

I am getting the error "At least one object must implement IComparable.", can someone explain me why iam I getting this error ?

1 Answer 1

4

You are calling grps.Max() to get maximnum item in group. Your anonymous objects are not comparable. How Linq will know which one is maximum from them? Should it use id property for comparison, or name?

I believe you want to select max salary:

maxsal = grps.Max(s => Int32.Parse(s.sal))
1
  • Thanks for the correction , but I didn't get the error once I replaces with the lamda expression you gave , so where Is the point of tyepe Icomparable here then ? I would like to know the story behind the Icomparable for linq sorting compared to sql sorting , can you help me understanding the same
    – Shekar
    Feb 25, 2014 at 15:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.