Select 使用 Linq 的组中的最大日期项目 VB.NET

Select Max Date items in group using Linq VB.NET

我有如图所示的数据。

NameA Date
NameA Date
NameA Date
NameB Date
NameB Date
NameC Date
NameD Date
NameD Date

我想让它返回如下,只获取最近日期的记录。我对 Linq 的语法感到困惑,我从下面开始,但我不确定该从哪里开始。

NameA Date
NameB Date
NameC Date
NameD Date

已启动 Linq

Dim pciLST = _
            From p As SmartFormData(Of PCISF) In pciSFM.GetList(m_Criteria) _
            Where p.SmartForm.EmployeeUsername.ToLower() = m_Username.ToLower() AndAlso _
                  IsOpen(p.SmartForm.CompletedDate, p.SmartForm.ActiveFor, p.SmartForm.Open)

回答

Dim pciLST = _
            From g In pciSFM.GetList(m_Criteria).AsEnumerable() _
            Where g.SmartForm.EmployeeUsername.ToLower() = m_Username.ToLower() _
            Order By (g.SmartForm.CompletedDate) Descending _
            Take 1 _
            Select _
                Name = IIf(g.SmartForm.FormName Is Nothing, "", g.SmartForm.FormName.ToString()), _
                DateSigned = IIf(g.SmartForm.CompletedDate IsNot Nothing AndAlso _
                                 Date.TryParse(g.SmartForm.CompletedDate, New Date()), g.SmartForm.CompletedDate, New Date(1, 1, 1)), _
                ActiveFor = IIf(g.SmartForm.ActiveFor Is Nothing, -1, Integer.Parse(g.SmartForm.ActiveFor)), _
                NewLink = IIf(g.SmartForm.NewLink Is Nothing, "", g.SmartForm.NewLink.ToString()), _
                ViewLink = IIf(g.SmartForm.ViewLink Is Nothing, "", g.SmartForm.ViewLink.ToString()), _
                Open = IIf(g.SmartForm.Open Is Nothing, -1, Integer.Parse(g.SmartForm.Open)), _
                Requirement = IIf(g.SmartForm.Requirement Is Nothing, "", g.SmartForm.Requirement.ToString()), _
                Archived = Boolean.Parse(g.SmartForm.Archived), _
                Id = Long.Parse(g.Content.Id), _
                Due = GetDue(Date.Parse(g.SmartForm.CompletedDate), Integer.Parse(g.SmartForm.ActiveFor))

        Return pciLST.AsQueryable()

此代码现在有效

public class NameDate
    Public Name As String
    Public D As DateTime
End Class
. . . . . 
Dim list As New List(Of NameDate)(4)
list.Add(New NameDate() With {.Name = "A", .D = DateTime.Now.AddDays(-10)})
list.Add(New NameDate() With {.Name = "A", .D = DateTime.Now})
list.Add(New NameDate() With {.Name = "B", .D = DateTime.Now.AddDays(-10)})
list.Add(New NameDate() With {.Name = "B", .D = DateTime.Now.AddDays(-20)})

Dim o = From nd In list _
        Group nd By nd.Name Into g = Group _
        Select New NameDate() With {.Name = g.First().Name, .D = g.Max(Function(x) x.D)}

o.ToList().ForEach(Sub(x) Debug.WriteLine(x.Name & " - - " & x.D.ToString()))

这里是原c#

var o = from nd in list
        group nd by nd.Name
        into g 
        select new NameDate() {Name = g.Key, Date = g.Max(d => d.Date)};