簡體   English   中英

從數據表中篩選行的最佳方法是什么?

[英]What is the optimal way to filter rows from a DataTable?

我正在尋找從數據表中獲取數據行的最簡單和最快的方法。 這些數據行有幾列,包括一列 Integer,我只想要具有最高值的行。

目前我得到這樣的結果:

Dim maxValue = 0
For Each row In mDataTable.Rows
If row.valueCell > maxValue Then
    maxValue = row.valueCell
    End If
Next
Dim mDataTableBis = mDataTable.Clone
For Each row In mDataTable.Select("value = " & valueCell)
    mDataTableBis.ImportRow(row)
Next

原始數據表(例如):

行數 字母 價值
第 1 行(通緝) X 4個
第 2 行 2個
第 3 行(通緝) z 4個

如果您更喜歡 for-each 循環方法,就像從您發布的代碼中看到的那樣,請使用此 function:

Public Sub ForEachLoop()

    Dim maxValue As Integer

    ' Loop through rows to find max value
    For Each row As DataRow In mDataTable.Rows
        Dim currentRowValue As Integer = row.Field(Of Integer)(numbersColumn)
        If currentRowValue > maxValue Then
            maxValue = currentRowValue
        End If
    Next

    ' Create a List of DataRow
    Dim res As New List(Of DataRow)

    ' Loop through rows again to add to list each row in which numbersColumn field = maxValue
    For Each row As DataRow In mDataTable.Rows
        If row.Field(Of Integer)(numbersColumn) = maxValue Then
            res.Add(row)
        End If
    Next

    ' Create results DataTable copying the List to a new DataTable
    Dim result As DataTable = res.CopyToDataTable()

End Sub

如果您想要更簡潔的內容,可以嘗試使用 LINQ,但這是一個更高級的解決方案,肯定對初學者不友好。

就像是:

Public Sub LINQ()

    ' Find the row with highest value in numbersColumn, then get the value from the field
    Dim maxValue As Integer = mDataTable.AsEnumerable().MaxBy(Function(x) x.Field(Of Integer)(numbersColumn)).Field(Of Integer)(numbersColumn)

    ' Select all the rows with numbersColumn value = maxValue (this returns an IEnumerable of DataRow)
    Dim resultsRows As IEnumerable(Of DataRow) = mDataTable.AsEnumerable().Where(Function(x) x.Field(Of Integer)(numbersColumn) = maxValue)

    ' Create results DataTable copying the IEnumerable to a new DataTable
    Dim result As DataTable = resultsRows.CopyToDataTable()

End Sub

您還可以使用DataTable.Select()方法...

Public Sub DataTableSelect()

    Dim result As DataTable = mDataTable.Select("numbersColumn = max(numbersColumn)").CopyToDataTable()

End Sub

...但這比 for each 循環要慢得多:

基准

如您所見,for each 版本比Select()版本快大約 3500 倍——這是一個很大的區別。 這個測試是在一個相對較小的大約 10k 行的 DataTable 上執行的——想象一下在一個百萬行的 DataTable 中會有多大的差異。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM