linq到使用vb.net的嵌套查询的强类型数据表

时间:2014-09-17 14:19:12

标签: vb.net linq datatable

我正在尝试将以下sql select * from tblPBRule where PBRuleId = 123 and StartDate < = '20140902' and finishdate is null and PBCodeid in (select PBCodeid from tblpbrule where PBHourstypeid IN (3,4,5,6))转换为应用程序

中的linq查询
 Dim query As IEnumerable(Of PBRuleData.PBRuleRow) = From s In Me.PBRule.PBRule.AsEnumerable() _
                                                                        Where s.PBRuleId = .PBRuleId And s.StartDate <= .PBDate _
                                                                        And ((s.IsFinishDateNull) OrElse (s.FinishDate > .PBDate)) Select s

任何人都可以帮我完成此查询

1 个答案:

答案 0 :(得分:0)

刚刚进行了相同的搜索,发现Brad的博客对我有用,就像下面的函数一样。

http://www.gorgando.com/blog/technology/asp-net/not-in-subquery-with-asp-net-linq-in-vb

希望这会有所帮助。第二个表的2个查询之间的唯一区别是&#34; Where Not&#34;因为没有条件。

Private Enum InOrNotInSelect
    None = 0
    InTable = 1
    NotInTable = 2
End Enum

Private Function getNotInData(firstTable As DataTable,
                              secondTable As DataTable,
                              inOrNotIn As InOrNotInSelect,
                              keyField As String) As DataTable

    ' TODO: make keyField a ParamArray 
    '       (don't know how to write dynamic LINQ code yet)

    Dim loTable As DataTable = Nothing

    ' first of all do a query on the first table 
    Dim firstQuery = From dt1 In firstTable.AsEnumerable()
                     Select dt1.Field(Of String)(keyField)

    If inOrNotIn = InOrNotInSelect.NotInTable Then
        ' next do a query on the second table returning the rows NOT IN the first table
        Dim inNotInQuery = From dt2 In secondTable.AsEnumerable()
                           Where Not firstQuery.Contains(dt2.Field(Of String)(keyField))
                           Select dt2

        ' convert the rows to a table
        loTable = inNotInQuery.CopyToDataTable()

    ElseIf inOrNotIn = InOrNotInSelect.InTable Then
        ' next do a query on the second table returning the rows IN the first table
        Dim inNotInQuery = From dt2 In secondTable.AsEnumerable()
                           Where firstQuery.Contains(dt2.Field(Of String)(keyField))
                           Select dt2

        ' convert the rows to a table
        loTable = inNotInQuery.CopyToDataTable()
    End If

    ' remove debug code in production build
    For Each dRow As DataRow In loTable.Rows
        Debug.Print(dRow(keyField) & " - " & dRow("FullName"))
    Next

    Return loTable
End Function