Linq:即使table为空,也要将表视为if语句中的任何内容

时间:2012-03-29 10:07:07

标签: .net vb.net linq if-statement

我正在做一个简单的linq请求:

    Dim r = (From p In db.Product _
             Where p.Product_ID = ProductID _                   
             Select p)

    If (r IsNot Nothing) Then
          'doing stuff here
    End If

我的问题是eventhought请求返回一个空表(我也试过了一个计数)它认为表不是空的并执行“if”中的代码......

知道来自哪里?

3 个答案:

答案 0 :(得分:1)

Linq将始终从此返回一些内容。即使它是一个空的IEnumerable(Of T)。尝试将If切换为If r.Any() Then,看看是否能为您提供所需的行为。

答案 1 :(得分:0)

如果您希望if语句中的代码只在查询返回某些值时执行,您应该使用类似的内容:

If (r IsNot Nothing AndAlso r.Any()) Then
          'doing stuff here
End If

答案 2 :(得分:0)

尝试以下操作来执行查询。我有时候已经远离VB,所以请原谅语法错误;)

Dim r = (From p In db.Product _
         Where p.Product_ID = ProductID _                   
         Select New(){productid = p.Product_ID}).ToList()

If (r.Count() > 0) Then
      'doing stuff here
End If