2015-02-05 206 views
1

我想基于两个单独的列表创建项目的单个列表,但ListA中的日期属性与ListB中的不同日期属性具有相同的值。我从我的FinalList中获取来自ListB的正确对象,但不是ListA中的对象。LINQ加入使用日期不工作

考虑以下数据

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包含对象Foo1Foo3,但我只得到Foo3

任何想法我做错了吗?

+0

您正在使用什么课?什么是安装日期?什么是删除日期?你为什么使用IList(Of Object)'?一些样本输入/输出如何?否则,这是不可能回答的。 – sloth 2015-02-05 15:36:49

+0

是'RemovalDate'类型,可以是什么? – Plutonix 2015-02-05 15:38:08

+0

@Plutonix请注意,VB.Net使用'Nothing'也可以获得类型的默认值(如C#的default())。 – sloth 2015-02-05 16:00:57

回答

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

因此,要获得Foo1Foo3,做一个简单的Join

Dim FinalList = (From LA In ListA 
       Join LB In ListB On LA.InstallDate Equals LB.RemovalDate).ToList() 

FinalList现在包含一个项目(因为有一个匹配)具有两个属性:

LA(Foo1)和LB(Foo2)

enter image description here


在回答您的评论:

要flaten列表,只需使用:

Dim FinalList = From LA In ListA 
       Join LB In ListB On LA.InstallDate Equals LB.RemovalDate 
       From item in {LA, LB} 
       Select item 

enter image description here

+0

我需要FinalList是一个单一的对象列表,以便以后迭代。 – empo 2015-02-06 10:04:18

+0

@empo请参阅我的编辑 – sloth 2015-02-06 10:16:05