【问题标题】:Get the id of the latest record in group by with linq使用linq获取group by中最新记录的id
【发布时间】:2021-01-20 13:00:43
【问题描述】:

我正在尝试获取 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)
      };

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

资产 LastSeen BS1 2020-05-10 BS2 2020-07-10

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

谢谢

【问题讨论】:

  • var latestPosition = Scan.OrderByDescending(x => x.LastSeen).GroupBy(x => x.Asset).Select(x => new {Asset = x.Key, LastSeen = x. First().LastSeen}).ToList();

标签: c# linq linq-to-sql entity-framework-core


【解决方案1】:

由于 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;

【讨论】:

  • 我认为您错过了解决此问题的非常常见的 LINQ 方法,jdweng 将其作为评论包含在内。
  • @StriplingWarrior,如果您认为这是可以接受的方法 - 请继续。我发现解决方法很慢,甚至无法转换为 SQL。
  • @StriplingWarrior 恕我直言,您和 jdweng 都忽略了 LINQ to Entities 与 LINQ to Objects 不同的事实。在 L2O 甚至 L2E(EF6) 中有效的方法不一定在 L2E(EF Core) 中有效。事实上,许多 GroupBy 构造(基本上除了简单的键/聚合之外的所有构造)目前在 EF Core 中都不起作用。
  • 你们两个是绝对正确的。我仍在使用 EF6,但不知道 EF Core 缺乏处理 GroupBy/FirstOrDefault 构造的能力。
  • @NoseBagUK, linq2db 永远不会与内存数据库一起使用。更糟糕的是 EF 团队想要弃用这种存储,但社区声称它很方便。所以他们必须支持这个变体。我认为更好的是在内存中设置 SQLite,这个查询就可以了。
【解决方案2】:

I think I did what you wanted above and I wrote the full code on this link

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

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

【讨论】:

  • 不幸的是,这不起作用,因为 LastSeen 对于同一资产并不总是唯一的
【解决方案3】:

所以每个Scan 都有一个属性Asset、一个日期时间属性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 值的扫描(选定的属性)。

【讨论】:

  • 回到这个问题并决定尝试一些解决方案,看看有没有比我的解决方案更好的地方。不幸的是,EF 无法将其转换为查询,无论如何谢谢
猜你喜欢
  • 2020-12-19
  • 1970-01-01
  • 2013-08-23
  • 2013-06-27
  • 2016-05-15
  • 2020-08-11
  • 2022-08-11
  • 2012-06-15
相关资源
最近更新 更多