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

时间:2015-07-14 18:32:16

标签: vb.net linq linq-to-sql

我有数据显示。

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)

ANSWER

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()

1 个答案:

答案 0 :(得分:2)

此代码现在正在使用

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