【问题标题】:Left outer join null reference error in LINQLINQ中的左外连接空引用错误
【发布时间】:2015-04-20 18:55:23
【问题描述】:

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

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) 上没有匹配的类型。我怎样才能安排查询,而不是这个错误,我只是得到一个值为 Nothing for Interval?

【问题讨论】:

    标签: vb.net linq join


    【解决方案1】:

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

    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
    

    结果很好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-22
      • 1970-01-01
      • 2015-01-04
      • 2011-04-27
      • 2011-08-04
      • 2011-03-25
      相关资源
      最近更新 更多