如何使用Max函数在多列上使用分组依据

本文关键字:Max 何使用 函数 | 更新日期: 2023-09-27 18:37:25

这是一个示例表,我将在其中提取优先级最高的记录,对应于每对 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)

如何使用Max函数在多列上使用分组依据

在类中创建公共属性并执行以下操作:

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)
                 };

您的类应如下所示:

public class MyObjectType
{
   public int Code { get; set; }
   public int Id { get ; set; }
   public int MaxValue { get; set; }
 }