2

我已经被这个难住了。我有一个相当大(~1500 x ~1000)的正整数和负整数数据表,只是我从 .csv 文件中获取的。对于我的程序,我需要找到整个表格的最大值,而不仅仅是单行或单列。最理想的情况是,代码会短小精悍,但情况并非总是如此;)。

我的 DataTable 的名称是BeamMap,我试图返回一个值MaxValue(已经声明为整数)。我可以根据要求发布用于创建 DataTable 的代码。

额外的信用:(不是真的)

有没有办法快速找到所述最大值的位置(即行、列)?到目前为止,我看到的所有示例都逐个单元格地检查预定值,这对于我拥有的数据点数量来说效率很低。

4

3 回答 3

10

您还可以使用 Compute("MAX(columnName),"") 方法来查找列上的最大值

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
于 2014-06-16T18:19:15.970 回答
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
于 2012-06-20T10:22:01.210 回答
0

我无法让 user3549709 的代码正常工作,因为不断收到“聚合参数中的语法错误:需要一个带有可能的 'Child' 限定符的单列参数。” 错误。我所有的表格都是手动填写的,并且没有从数据库中获取数据——我不知道这是否会有所不同。

这是我用来查找最小值和最大值的方法:

    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

注意:如果列名中有空格等,则只需要方括号 []

于 2016-07-06T13:48:25.900 回答