解析DataTable以匹配值并从结果中创建新的DataTable

时间:2017-01-17 21:18:34

标签: vb.net datatables duplicates

在VB.NET中,我试图计算列表中的值,直到我的DataTable,Boxes中的“stock”值等于列表中的值。发生这种情况时,应在我的新DataTable“输出”中创建一行。然后,我将继续计算列表,查找要添加到“输出”的其他匹配实例。

到目前为止,通过列表计数,然后在该计数内通过数据表来匹配值的工作非常好。我要挂断的部分是当我尝试将匹配的行放到另一个表中时。

Dim output As DataTable
Dim jsonstringy As String = BoxComms.WebGet("http://foo.foo.foo")        'PULLS JSON STRING
Dim Boxes = Newtonsoft.Json.JsonConvert.DeserializeObject(Of DataTable)(jsonstring)
Dim MyString As String = TextBox1.Text               'MAKE STRING OF STOCK #'s FROM TEXTBOX
MyString = MyString.Replace(" ", "")                                     'GET RID OF SPACES
Dim MyArray() As String = MyString.Split(",")                'SEPERATE COMMA DELIMETED LIST
Dim MyList As List(Of String) = MyArray.ToList()

For Each value In MyList                                   'COUNT THROUGH LIST OF STOCK #'s
    For Each row As DataRow In Boxes.Rows
        If row("stock") = value Then      'IF STOCK # IS EQUAL TO ANY OF NUMBERS IN TEXTBOX
            output.ImportRow(row)         'ADD ROW FROM DATATABLE Boxes to DATATABLE output
        End If
    Next row
Next

1 个答案:

答案 0 :(得分:0)

解决方案非常简单,我的DataTable首先需要一个架构。为了复制模式,我需要的是将新表初始化为克隆。这样做的代码如下。

Dim output As DataTable = Boxes.Clone()

克隆与复制。 copy get是架构,数据克隆只获取架构。然后当我通过第一个表解析匹配时,我必须使用以下代码将行添加到我的新表中。

output.Rows.Add(row.ItemArray)

完整代码如下

        Dim jsonstring As String = BoxComms.WebGet("https://foo.foo.foo")
        Dim Boxes = Newtonsoft.Json.JsonConvert.DeserializeObject(Of DataTable)(jsonstring)
        Dim output As DataTable = Boxes.Clone()
        Dim MyString As String = TextBox1.Text
        MyString = MyString.Replace(" ", "")
        Dim MyArray() As String = MyString.Split(",")
        Dim MyList As List(Of String) = MyArray.ToList()
        For Each value In MyList
            For Each row As DataRow In Boxes.Rows
                If row("stock") = value Then
                    Console.WriteLine(row("stock"))
                    output.Rows.Add(row.ItemArray)
                End If
            Next row
        Next
        BoxControl.DataGridView1.DataSource = output
        Me.Close()
    End If