Matt Matt - 4 months ago 30
Vb.net Question

Find the maximum value of a VB.Net DataTable

I have been very stumped by this one. I have a fairly large (~1500 x ~1000) DataTable of positive and negative integers only that I acquired from a .csv file. For my program, I need to find the maximum value of the entire table, not just in a single row or column. Optimally, the code would be short and sweet, but that's not always the case ;).

The name of my DataTable is

BeamMap
and I am trying to return a value of
MaxValue
(already declared as an integer). I can post the code I have for creating the DataTable upon request.

Extra Credit: (not really)

Is there a way to quickly find the location (ie., row,column) of said maximum value? So far, all of the examples I've seen check cell by cell for a predetermined value, which is rather inefficient for the number of data points that I have.

Answer

This code will do it. I haven't tried with a huge datatable so you will have to see how long it takes:

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

It sorts each column in turn and if the first value is larger than the current largest value it updates it.

For the extra credit you can do this but there might be a performance hit doing the IndexOf to find the 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
Comments