繁体   English   中英

使用 linq 获取 group by 中最新记录的 id

[英]Get the id of the latest record in group by with linq

我正在尝试获取 linq 中某个组的最新记录,但我想要 ID,而不是日期,因为有时日期可能与其他记录完全相同。

以下代码为我提供了密钥和最后日期

var latestPositions = from bs in Scan
     group bs by bs.Asset into op
     select new
     {
        Asset = op.Key,
        LastSeen = op.Max(x => x.LastSeen)
      };

返回这样的东西......

Asset      LastSeen
BS1        2020-05-10
BS2        2020-07-10

这是我需要的,但是我需要从该表行中获取其余数据,但是如果我将它连接到两列上,我可以获得多行,有没有办法让我返回 id 列该组由,所以我可以加入?

谢谢

由于 SQL 限制,GroupBy 在这里无法提供帮助。 但是你可以写解决方法

var latestPositions = from bs in Scan
   where !Scan.Any(s => s.Asset == bs.Asset && s.LastSeen > bs.LastSeen)
   select bs;

但我不得不提一下,最快的方法是使用 EF Core 中不可用的窗口函数:

SELET 
   sc.Id
FROM (
   SELECT 
      s.Id,
      ROW_NUMBER() OVER (PARTITION BY s.Asset ORDER BY s.LastSeen DESC) AS RN
   FROM Scan s
) sc
WHERE sc.RN == 1

但是存在 EF Core 扩展linq2db.EntityFrameworkCore这使得通过 LINQ 成为可能(我假设 Asset 只是 ID,而不是导航属性)

var queryRn = from bs in Scan
   select new 
   {
      Entity = bs,
      RN = Sql.Ext.RowNumber().Over()
        .PartitionBy(bs.Asset).OrderByDesc(bs.LastSeen).ToValue()
   };

 // switch to alternative translator
 queryRn = queryRn.ToLinqToDB();

 var latestPositions = from q in queryRn
    where q.RN == 1
    select q.Entity;

我想我做了你上面想要的,我在这个链接上写了完整的代码

如果不是你想要的,你能不能把你想要的写得更清楚一点。

var temp = from l in list
       group l by l.Asset into lg
       orderby lg.Key
       select new { Asset = lg.Key, LastSeen = lg.Max(x => x.LastSeen), ID = lg.Where(x => x.LastSeen == lg.Max(y => y.LastSeen)).Single().ID };

因此,每个Scan都有一个属性Asset 、一个 DateTime 属性LastSeen以及零个或多个其他属性。

要求:给定一系列扫描,给我 LastSeen 扫描的每个资产(全部或部分)属性。

以下将解决问题:

var lastSeenScan = dbContext.Scans.GroupBy(scan => scan.Asset,

    // parameter resultSelector: take every Asset, and all Scans that have this Asset value
    // and order these Scans by descending value of lastSeen:
    (asset, scansWithThisAssetValue) => scansWithThisAssetValue
        .OrderByDescending(scan => scan.LastSeen)

        // Select the scan properties that you plan to use.
        // Not needed if you want the complete Scan
        .Select(scan => new
        {
            Id = scan.Id,
            Operator = scan.Operator,
            ...
        })

        // and keep only the First one, which is the Last seen one:
        .FirstOrDefault();

换句话说:将您的扫描表分成具有相同属性资产值的扫描组。 按 LastSeen 的降序值对每组中的所有扫描进行排序。 这将使上次看到的扫描成为第一个。

从组中的所有扫描中仅选择您计划使用的属性,并选择第一个。

结果:对于每个使用过的资产,您将获得具有最高 LastSeen 值的(所选属性)扫描。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM