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();
我收到错误“至少有一个对象必须实现IComparable。”,有人可以解释一下为什么我会收到此错误吗?
答案 0 :(得分:4)
您正在呼叫grps.Max()
以获取群组中的maximnum项目。您的匿名对象无法比较。 Linq如何知道哪一个最大?它应该使用id
属性进行比较,还是使用name
?
我相信你想选择最高工资:
maxsal = grps.Max(s => Int32.Parse(s.sal))