Visual Basic LINQ错误

时间:2012-04-15 15:03:38

标签: .net vb.net linq exception-handling nullreferenceexception

任何人都知道我为什么会遇到这个错误?

我收到以下错误:

  

对象引用未设置为对象的实例

这是LINQ问题。感谢您提前提供任何帮助。

Dim q = From line In seats
        Let data = line.Split(New [Char]() {" "c}, StringSplitOptions.RemoveEmptyEntries) ' it occurs in this line '
        Let seatA = data(0)
        Let seatB = data(1)
        Let seatC = data(2)
        Let seatD = data(3)
        Let seatE = data(4)
        Let seatF = data(5)
        Where seatA Is "."
        Where seatB Is "."
        Select seatA, seatF

2 个答案:

答案 0 :(得分:1)

如果将第一行更改为:

,它是否有效
Dim windowSeatQuery = From line In seats.Where(function (s) s isnot nothing)

这表示席位列表中存在空值,上面的Where lambda应该删除它们。

答案 1 :(得分:0)

你的Where子句对我来说很奇怪。你不应该使用=运算符,而不是Is:

Dim q = From line In seats
    Let data = line.Split(New [Char]() {" "c}, StringSplitOptions.RemoveEmptyEntries) ' it occurs in this line '
    Let seatA = data(0)
    Let seatB = data(1)
    Let seatC = data(2)
    Let seatD = data(3)
    Let seatE = data(4)
    Let seatF = data(5)
Where seatA = "." AndAlso seatB = "."   '<------   Use = on this line not Is
Select seatA, seatF

你确定每一行都用空格而不是别的分隔吗?即使有在那里也不应该导致空参考。

这是我的示例程序似乎工作(在LinqPad中测试,它似乎不支持隐式行继续符):

Sub Main
    Dim seats As New List(Of String)()
    seats.Add("1 2 3 4 5 6")
    seats.Add(". . 9 8 7 6")
    seats.Add(". . 5 5 5 5")
    seats.Add("1 2 3 4 5 6")
    seats.Add(". . 2 4 6 8")
    seats.Add("1 2 3 4 5 6")

    Dim q = From line In seats _
        Let data = line.Split(New [Char]() {" "c}, StringSplitOptions.RemoveEmptyEntries) _
        Let seatA = data(0) _
        Let seatB = data(1) _
        Let seatC = data(2) _
        Let seatD = data(3) _
        Let seatE = data(4) _
        Let seatF = data(5) _
    Where seatA = "." AndAlso seatB = "." _
    Select seatA, seatF

    q.Dump()
End Sub