如何合并DataRow()

时间:2018-01-03 20:42:24

标签: vb.net

我有一个DataTable(dt)我需要在某些条件下过滤我只能使用'Select'。我编写了可行的代码,但我想做得更好:

        Dim result As DataTable = dt.Clone
        Dim r1 As DataRow() = Nothing
        Dim r2 As DataRow() = Nothing
        Dim r3 As DataRow() = Nothing
        If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then
            r1 = dt.Select("A < " & Quote(Date.UtcNow) & " AND B IS NULL")
            r2 = dt.Select("B > " & Quote(Date.UtcNow) & " AND A IS NULL")
            r3 = dt.Select("A < " & Quote(Date.UtcNow) & " AND B > " & Quote(Date.UtcNow))
        End If

        For i As Integer = 0 To r1.Length -1
            result.ImportRow(r1(i))
        Next
        For i As Integer = 0 To r2.Length -1
            result.ImportRow(r2(i))
        Next
        For i As Integer = 0 To r3.Length -1
            result.ImportRow(r3(i))
        Next

我找不到任何解决方法来保存结果dt.Select到一个DataRow()对象,然后只做一个For循环。我在寻求建议, 谢谢!

1 个答案:

答案 0 :(得分:0)

早上我醒来后头脑清醒,本来应该是显而易见的事情对我来说是一个可怕的时间 - OR - 它解决了问题+ CopyToDataTable()

    If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then
        dt = dt.Select("(A < " & Quote(Date.UtcNow) & " AND B IS NULL) OR (B > " & Quote(Date.UtcNow) & " AND A IS NULL) OR (A < " & Quote(Date.UtcNow) & " AND B  > " & Quote(Date.UtcNow) & ")").CopyToDataTable()
    End If

    Return dt

感谢您的时间,特别是 jmcilhinney