gpt4 book ai didi

c# - 我如何使用 Linq/Linq to Sql 来执行此操作?

转载 作者:太空宇宙 更新时间:2023-11-03 20:41:55 25 4
gpt4 key购买 nike

我有一个审计表,我正在尝试使用 Linq 来弄清楚如何获取所有人最近的审计操作。我只是不确定如何。

示例架构

审计表(技术上它实际上是一个 View )

AuditId   UserName   Action    CreatedOn
1 Bob Action1 2000-01-01
2 Bob Action2 2000-01-02
3 Bob Action8 2000-01-03
4 Jane Action1 2000-01-01
5 Bob Action1 2000-01-05
6 Jane Action3 2000-01-05
7 Andrew Action4 2000-01-05
8 Siena Action1 2000-01-06
9 Sarah Action1 2000-01-07
10 Harry Action6 2000-01-09

所以,对于结果,我会在......

5, Bob, Action1, 2000-01-05
6, Jane, Action3, 2000-01-05
7, Andrew, Action4, 2000-01-05
8, Siena, Action1, 2000-01-06
9, Sarah, Action1, 2000-01-07
10, Harry, Action6, 2000-01-09

有人可以帮忙吗?

(哦,如果我需要索引某些东西,请建议哪一列)。

谢谢:)

最佳答案

我认为它看起来像这样:

var query = from action in db.Actions
orderby action.CreatedOn descending
group action by action.UserName into groupedActions
let mostRecent = groupedActions.First()
select new { UserName = groupedActions.Key,
LatestId = mostRecent.AuditId,
LatestAction = mostRecent.Action,
LatestDate = mostRecent.CreatedOn };

如评论中所述,这适用于 LINQ to Objects,但分组可能不会保留 SQL 中的顺序。此外,“最新”记录可能会为您提供所需的一切。这是解决这两点的另一个查询:

var query = from action in db.Actions
group action by action.UserName into groupedActions
select groupedActions.OrderByDescending(a => a.CreatedOn).First();

为 CreatedOn 和 UserName 添加索引。

关于c# - 我如何使用 Linq/Linq to Sql 来执行此操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2278999/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com