如何使用LINQ选择最新的和不同的记录? [英] How can I select the most recent and distinct records using LINQ?
本文介绍了如何使用LINQ选择最新的和不同的记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用LINQ从状态历史记录中获取记录的最新状态.我在下订单时遇到麻烦,或者我完全不合时宜.
I'm trying to get the latest status of a recorded from a history of statuses using LINQ. I'm having trouble with my order or maybe I'm completely off the mark.
我的代码
Dim LatestStatusTable= (From RecordHistoryTable In db.RecordHistory) _
.GroupBy(Function(i) i.Status).[Select](Function(i) i.First())
示例数据
Data
ID Timestamp Status
251 2017-07-19 11:01:15.577 2
250 2017-07-14 16:15:38.543 2
249 2017-07-13 13:31:13.010 2
249 2017-07-14 04:16:08.307 1
249 2017-07-14 05:45:38.437 2
249 2017-07-14 08:00:42.253 1
249 2017-07-14 08:30:02.380 2
248 2017-07-11 15:30:28.223 2
248 2017-07-11 18:31:11.857 1
248 2017-07-11 18:49:08.510 2
Desired Output
ID Timestamp Status
251 2017-07-19 11:01:15.577 2
250 2017-07-14 16:15:38.543 2
249 2017-07-14 08:30:02.380 2
248 2017-07-11 18:49:08.510 2
有人可以教育我并指出正确的方向吗?
Can someone please educate me and point me in the right direction?
推荐答案
GroupBy ID
然后选择时,要在Timestamp
上选择OrderByDescending
,然后在每个组中使用First
.
GroupBy ID
then when selecting, you want to OrderByDescending
on Timestamp
, then take the First
in each group.
Dim LatestStatusTable = (From RecordHistoryTable In db.RecordHistory) _
.GroupBy(Function(i) i.ID) _
.[Select](Function(g) g.OrderByDescending(Function(x) x.Timestamp).First())
这篇关于如何使用LINQ选择最新的和不同的记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文