如何按日期和 select 最大(日期)、主键和外键对 class 进行分组?

How to group a class by date and select Max(Date), primary-key and foreign-key?

我需要减少 class 中的数据,如下所示(PK ... 主键,FK ... 外键):

我使用 linq 尝试了以下几种变体

var groupedClass = from record in records
               group new {
                   record.Date
               }
               by new{
                   record.FK,
                   //record.PK  //  when included then resulting data are not distinct regarding FK
               }
               into g
               select new{
                   MaxDate = g.Max(r => r.Date),
                   SelectedFK = g.key.FK,
                   //SelectedPK = g.key.PK    // gives an error when PK is not inluced in by new
               };

但我无法将不同的 PK、FK 和 Max(date) 放入分组数据集中。请帮忙!

FK分组,然后用MaxBy到select每组最大日期的记录:

var groupedClass = records
    .GroupBy(record => record.FK)
    .Select(grp => grp.MaxBy(record => record.Date));

工作示例:https://dotnetfiddle.net/9Pe4Z4


如果您不使用 .NET 6,则 MaxBy 将不可用,因此您可以改用 OrderByDescendingFirst

var groupedClass = records
    .GroupBy(record => record.FK)
    .Select(grp => grp.OrderByDescending(record => record.Date).First());