LINQ查询只获取最新项目

时间:2015-10-06 08:09:22

标签: vb.net linq

我在考虑获取最新项目时遇到LINQ查询问题 我拥有的数据示例(左)和我需要选择的内容(右):

Name  Notes DateRecorded  Name  Notes DateRecorded
Item1 A     1.1.2015      Item1 C     1.3.2015
Item1 B     1.2.2015      Item2 X     1.2.2015
Item1 C     1.3.2015
Item2 X     1.2.2015  

Class Properties
  Name As String
  Notes As String
  DateRecorded As Date
End Class

1 个答案:

答案 0 :(得分:3)

So you want to group by Name and select the newest by DateRecorded:

Dim newestProps = props.GroupBy(Function(p) p.Name).
    Select(Function(grp) grp.OrderByDescending(Function(p) p.DateRecorded).First())

In query syntax:

newestProps = From p In props
              Order By p.DateRecorded Descending
              Group p By p.Name Into orderedNameGroup = Group
              Select orderedNameGroup.First()