如何在Linq中过滤多个if条件的列表

时间:2017-03-16 12:24:32

标签: vb.net linq

我有一些包含一些对象的列表。我需要在该列表中执行linq以获得另一个列表“子列表”,具有以下条件 1)如果项目状态为“完成”且完成日期为5天,则包含在子列表中 2)如果项目状态为“待定”且截止日期少于7天,则包括在子列表中

如何使用单个linq查询实现此目的? 感谢您的支持

1 个答案:

答案 0 :(得分:1)

您可以将IEnumerable.Where方法与具有条件的谓词一起使用。由于我不了解你的对象模型,我将以一个例子来展示:

Public Class SomeObject
    Public Property Status As String
    Public Property Complete As DateTime?
    Public Property DueDate As DateTime?

    Public Sub New(strStatus As String, dteComplete As DateTime?, dteDueDate As DateTime?)
        Status = strStatus
        Complete = dteComplete
        DueDate = dteDueDate
    End Sub
End Class

一些数据填充:

Dim lstObjects As New List(Of SomeObject)

lstObjects.Add(New SomeObject("Complete", DateTime.Now.AddDays(-1), DateTime.Now.AddDays(-1)))
lstObjects.Add(New SomeObject("Pending", Nothing, DateTime.Now.AddDays(5)))
lstObjects.Add(New SomeObject("Pending", Nothing, DateTime.Now.AddDays(10)))    

这就是你如何查询它(返回两个结果):

Dim sublist As List(Of SomeObject) = lstObjects.Where(Function(target As SomeObject)
                                                          Dim bolMatch As Boolean = False

                                                          If (target.Status = "complete" AndAlso
                                                              target.Complete > DateTime.Now.Date.AddDays(-5)) OrElse
                                                             (target.Status = "pending" AndAlso
                                                              target.DueDate < DateTime.Now.Date.AddDays(7)) Then
                                                              bolMatch = True
                                                          End If

                                                          Return bolMatch
                                                      End Function).ToList()