2012-06-20 168 views
1

我一直非常難過這個。我有一個相當大的(〜1500 x〜1000)DataTable的正和負整數只有,我從一個.csv文件獲得。對於我的程序,我需要找到整個表的最大值,而不僅僅是一行或一列。最理想的情況是,代碼將簡短而甜蜜,但情況並非總是如此;)。找到一個VB.Net DataTable的最大值

我的DataTable的名稱是BeamMap,我試圖返回一個值MaxValue(已經聲明爲整數)。我可以根據要求發佈創建DataTable的代碼。

附加題:(不是真的)

有沒有辦法來快速找到位置所述最大值(即,行,列。)?到目前爲止,我所見過的所有例子都是逐個檢查一個預定的值,這對於我擁有的數據點數量來說效率相當低。

+0

是你在運行程序時讀取csv文件?如果是這樣,你能在那個階段檢查最小和最大值嗎? –

+0

@AndrewMorton,當我運行該程序時,我從csv文件加載數據(由用戶打開文件對話框選擇)並立即將其存儲到DataTable中。如果我能在那個階段檢查,我不知道如何。 – Matt

+1

類似的問題已經在這裏解答http://stackoverflow.com/questions/7995526/return-max-value-with-linq-query-in-vbnet – nik

回答

1

此代碼將執行此操作。我還沒有與一個巨大的數據表試過,所以你就要看看需要多長時間:

Private Function FindMaxDataTableValue(ByRef dt As DataTable) As Integer 
    Dim currentValue As Integer, maxValue As Integer 
    Dim dv As DataView = dt.DefaultView 
    For c As Integer = 0 To dt.Columns.Count - 1 
     dv.Sort = dt.Columns(c).ColumnName + " DESC" 
     currentValue = CInt(dv(0).Item(c)) 
     If currentValue > maxValue Then maxValue = currentValue 
    Next 
    Return maxValue 
End Function 

這反過來排序每一列,如果第一個值大於當前最大值大它將更新它。

對於額外的信用,你可以這樣做,但有可能是一個性能命中做IndexOf找到rowIndex

Private Function FindMaxDataTableValue(ByRef dt As DataTable) As Integer 
    Dim currentValue As Integer, maxValue As Integer 
    Dim rowIndex As Integer, colIndex As Integer 
    Dim dv As DataView = dt.DefaultView 
    For c As Integer = 0 To dt.Columns.Count - 1 
     dv.Sort = dt.Columns(c).ColumnName + " DESC" 
     currentValue = CInt(dv(0).Item(c)) 
     If currentValue > maxValue Then 
      rowIndex = dt.Rows.IndexOf(dv(0).Row) 
      colIndex = c 
      maxValue = currentValue 
     End If 
    Next 
    Debug.WriteLine("Max value found at Col:" + colIndex.ToString + " Row:" + rowIndex.ToString) 
    Return maxValue 
End Function 
6

您還可以使用計算(「MAX(列名),」「)方法對列

Private Function FindMaxDataTableValue(ByRef dt As DataTable) As Integer 

    Dim currentValue As Integer, maxValue As Integer 
    maxValue = 0 

    For c As Integer = 0 To dt.Columns.Count - 1 
     currentValue = dt.Compute("MAX(c)", "") 
     If currentValue > maxValue Then maxValue = currentValue 
    Next 
    Return maxValue 

End Function 
0

我無法獲得作爲一直得到user3549709的代碼工作找到最大值「在總的說法語法錯誤:期待與可能的‘兒童’限定單個列的說法。」的錯誤我所有的桌子充滿manu盟友,並沒有從數據庫中獲取他們的數據 - 我不知道這是否有所作爲。

這是我用來代替找到最小值和最大值:

Dim intcurrentValue As Integer 
    Dim intmaxValue As Integer 
    Dim intMinValue As Integer 

    intmaxValue = 0 
    intMinValue = 0 

    For Each colMyColumn As DataColumn In dtDelta_E.Columns 
     intcurrentValue = dtDelta_E.Compute("MAX([" & colMyColumn.ColumnName & "])", "") 
     If intcurrentValue > intmaxValue Then intmaxValue = intcurrentValue 
     intcurrentValue = dtDelta_E.Compute("MIN([" & colMyColumn.ColumnName & "])", "") 
     If intcurrentValue < intMinValue Then intMinValue = intcurrentValue 
    Next 

注意:您只需要在方括號[]如果您有空格或類似列名

相關問題