如何在具有 Max 函数的多列上使用 group by
How to use group by on multiple columns with Max function
这里有一个示例table,我将在其中提取优先级最高的记录,对应于每对ID和代码,如下:
这是我达到目标的方法:
var max = from item in items
group item by new {item.code, item.id} into r
select new MyObjectType(r.Select(q => q.code),
r.Select(q => q.id),
r.Max(q => q.priority));
但是结果为空...
有解决问题的办法吗?!
编辑:
这是一个简单的例子:
(code,id,priority)
(1,10,100)
(1,10,200)
(1,11,300)
(1,11,400)
(2,12,500)
(2,12,600)
(2,13,700)
(2,13,800)
而查询的结果应该是:
(1,10,200)
(1,11,400)
(2,12,600)
(2,13,800)
在 class 中创建 public 属性,然后这样做:
var max = from item in items
group item by new {item.code, item.id} into r
select new MyObjectType
{
Code = r.Key.code,
Id = r.Key.id,
MaxValue = r.Max(q => q.priority)
};
您的 class 应如下所示:
public class MyObjectType
{
public int Code { get; set; }
public int Id { get ; set; }
public int MaxValue { get; set; }
}
这里有一个示例table,我将在其中提取优先级最高的记录,对应于每对ID和代码,如下:
这是我达到目标的方法:
var max = from item in items
group item by new {item.code, item.id} into r
select new MyObjectType(r.Select(q => q.code),
r.Select(q => q.id),
r.Max(q => q.priority));
但是结果为空...
有解决问题的办法吗?!
编辑:
这是一个简单的例子:
(code,id,priority)
(1,10,100)
(1,10,200)
(1,11,300)
(1,11,400)
(2,12,500)
(2,12,600)
(2,13,700)
(2,13,800)
而查询的结果应该是:
(1,10,200)
(1,11,400)
(2,12,600)
(2,13,800)
在 class 中创建 public 属性,然后这样做:
var max = from item in items
group item by new {item.code, item.id} into r
select new MyObjectType
{
Code = r.Key.code,
Id = r.Key.id,
MaxValue = r.Max(q => q.priority)
};
您的 class 应如下所示:
public class MyObjectType
{
public int Code { get; set; }
public int Id { get ; set; }
public int MaxValue { get; set; }
}