LINQ中的左外连接空引用错误

时间:2015-04-20 18:55:24

标签: vb.net linq join

我有以下代码(或类似的东西):

Public Sub Load()
    Dim equipServices = {New Pair(20, 6), New Pair(21, 10), New Pair(22, 1)}
    Dim serviceTypes = {New Pair(1, 2), New Pair(6, 3), New Pair(9, 3)}
    Dim serviceIntervals = {New Pair(1, 0), New Pair(2, 0), New Pair(3, 0)}
    Dim equipmentList = _
        (From Service In equipServices _
         Group Join Type In serviceTypes On Service.second Equals Type.first Into Types = Group
         From Type In Types.DefaultIfEmpty()
         Group Join Interval In serviceIntervals On Type.second Equals Interval.first Into Intervals = Group
         From Interval In Intervals.DefaultIfEmpty()).ToList()
End Sub

Private Class Pair
    Public first As Integer
    Public second As Integer

    Public Sub New(first As Integer, second As Integer)
        Me.first = first
        Me.second = second
    End Sub
End Class

基本上,我试图在服务上进行类型的左外连接,然后是类型上的间隔的左外连接。当尝试使用Interval连接Type时,这会在Type.second上抛出System.NullReferenceException。我假设这是因为在第二个服务对(21,10)上没有匹配的类型。我如何安排查询,以便代替此错误,我只得到一个Nval for Interval的值?

1 个答案:

答案 0 :(得分:0)

事实证明,你可以在加入过程中检查“Nothing”。我替换了这一行:

Group Join Interval In serviceIntervals On Type.second Equals Interval.first Into Intervals = Group

这一行:

Group Join Interval In serviceIntervals On If(IsNothing(Type), Nothing, Type.second) Equals Interval.first Into Intervals = Group

并且效果很好。