我正在尝试基于两个单独的列表创建单个项目列表,但其中ListA的日期属性与ListB中的不同日期属性的值相同。我在FinalList中从ListB获取了正确的对象,但没有在ListA中获取对象。
考虑以下数据
Public Class Foo
Public Property InstallDate As Nullable(Of Date)
'getters/ setters
End Property
Public Property RemovalDate As Nullable(Of Date)
'getters/ setters
End Property
End Class
Dim Foo1 As New Foo()
Foo1.InstallDate = 01/12/2014
Foo1.RemovalDate = Nothing
Dim Foo2 As New Foo()
Foo2.InstallDate = 02/12/2014
Foo2.RemovalDate = Nothing
Dim Foo3 As New Foo()
Foo3.InstallDate = 01/01/2001
Foo3.RemovalDate = 01/12/2014
Dim OriginalList As IList(Of Foo) = {
Foo1,
Foo2,
Foo3
}
我的代码
Dim ListA As IList(Of Foo) =
(From X In OriginalList
Where X.InstallDate IsNot Nothing And X.RemovalDate Is Nothing
Select X).ToList()
Dim ListB As IList(Of Foo) =
(From X In OriginalList
Where X.RemovalDate IsNot Nothing
Select X).ToList()
Dim FinalList As IList(Of Foo) =
(From LA In ListA
Group Join LB In ListB On ListA.InstallDate Equals ListB.RemovalDate Into Group _
From grp In Group.DefaultIfEmpty()
Select grp).ToList()
所以我希望FinalList
包含对象Foo1
和Foo3
,但我只得到Foo3
任何想法我做错了什么?
答案 0 :(得分:0)
我已经更正了您的代码:
Public Class Foo
Public Property InstallDate As Nullable(Of Date)
Public Property RemovalDate As Nullable(Of Date)
End Class
Dim Foo1 As New Foo()
Foo1.InstallDate = #01/12/2014#
Foo1.RemovalDate = Nothing
Dim Foo2 As New Foo()
Foo2.InstallDate = #02/12/2014#
Foo2.RemovalDate = Nothing
Dim Foo3 As New Foo()
Foo3.InstallDate = #01/01/2001#
Foo3.RemovalDate = #1/12/2014#
Dim OriginalList As IList(Of Foo) = {
Foo1,
Foo2,
Foo3
}
Dim ListA = (From X In OriginalList
Where X.InstallDate IsNot Nothing AndAlso X.RemovalDate Is Nothing
Select X).ToList()
Dim ListB = (From X In OriginalList
Where X.RemovalDate IsNot Nothing
Select X).ToList()
所以,要获得Foo1
和Foo3
,请执行简单的Join
:
Dim FinalList = (From LA In ListA
Join LB In ListB On LA.InstallDate Equals LB.RemovalDate).ToList()
FinalList
现在包含一个项目(因为只有一个匹配),有两个属性:
LA
(Foo1)和LB
(Foo2)
回应你的评论:
要展开列表,只需使用:
Dim FinalList = From LA In ListA
Join LB In ListB On LA.InstallDate Equals LB.RemovalDate
From item in {LA, LB}
Select item