如何过滤数据表

时间:2017-03-06 23:56:22

标签: vb.net filter datatable

如何过滤数据表如下?

我有两个数据表作为[cancelledOrders]和[allOrders] n我的vb.net表单中的两个都有一个列名[OrderNo]。

我想要做的是过滤[allOrders]数据表,其中[OrderNo]列不包含任何等于[cancelledOrders]的[OrderNo]列中的值的值。

我尝试使用List of String。但我没有成功。请有人帮助我。

由于

2 个答案:

答案 0 :(得分:1)

我会在SQL查询中过滤。它看起来像这样:

  

SELECT allOrders。* FROM allOrders WHERE NOT EXISTS(SELECT * FROM   cancelledOrders WHERE cancelledOrders.orderno = allOrders.orderno)

答案 1 :(得分:0)

您的问题不清楚是否需要展览过滤器或数据获取过滤器,因此我将假设后者。我假设您的[OrderNo]列都是Integer类型。所以你走了:

Function FilterCancelledOrders(allOrders As DataTable, cancelledOrders As DataTable) As DataRow

    ' Let's use LInQ to collect all the numbers of cancelledOrders into an Array Of Integer
    Dim CancelledOrderNos = cancelledOrders.Select.Select(
        Function(dr) dr.Field(Of Integer)("OrderNo")).ToArray

    ' Now let's collect all dataRows from allOrders where OrderNo is contained in the Array of Integer we just got above:
    Dim CancelledOrderRows = allOrders.Select.Where(
        Function(dr) CancelledOrderNos.Contains(dr.Field(Of Integer)("OrderNo"))).ToArray

    ' If this is enough for your needs, now you have an Array of DataRow containing 
    ' all rows in [allOrders] whose [OrderNo] field info is contained in the corresponding 
    ' field of any row in [cancelledOrders]
    Return CancelledOrderRows  
End Function

编辑:此版本隐藏了未选择的行:

Sub FilterCancelledOrders(allOrdersView As DataGridView, cancelledOrders As DataTable, dgview as DataGridView)

    ' so far, same as before, but type String
    Dim CancelledOrderNos = cancelledOrders.Select.Select(
        Function(dr) dr.Field(Of String)("OrderNo")).ToArray

    ' iterate through DataGridView's rows
    For each dgvr as DataGridViewRow in dgview.Rows

        ' set row visibility according to your criterium
        dgvr.Visible = Not CancelledOrderNos.Contains(dgvr.Cells("OrderNo").Value)

    Next

    ' it's done!

End Sub

OR ELSE 您可以创建过滤的数据表并将其设置为DataGridView的数据源:

Function GetPositiveOrdersDataTable(allOrders As DataTable, cancelledOrders As DataTable) As DataTable

    Dim CancelledOrderNos = cancelledOrders.Select.Select(
        Function(dr) dr.Field(Of Integer)("OrderNo")).ToArray

    ' Collect all dataRows from allOrders where OrderNo is NOT contained in the Array of Integer we just got above:
    Dim positiveOrderRows = allOrders.Select.Where(
        Function(dr) Not CancelledOrderNos.Contains(dr.Field(Of Integer)("OrderNo"))).ToArray

    ' create empty table with same structure as allOrders
    Dim positiveOrders = allOrders.Clone()

    ' populate it with orders that were not cancelled
    For each dr in positiveOrderRows
        positiveOrders.ImportRow(dr)
    Next

    Return positiveOrders
End Function