Datagridview,如何在特定范围内获得最小值,最大值和平均值

时间:2016-07-13 14:49:17

标签: vb.net datagridview

我有一个包含1000个数据点的DataGridView。我已经成功计算了DataGridView中值的最小值,最大值和平均值,但现在我想从某个范围获得最小值,最大值和平均值。例如,101到200或201到300的数据。

For i As Integer = 0 To dataGridView1.Rows.Count() - 1 Step +1

    sum_tmp = sum_tmp + dataGridView1.Rows(i).Cells(2).Value

    If i = 0 Then
        max_tmp = dataGridView1.Rows(i).Cells(2).Value
        min_tmp = dataGridView1.Rows(i).Cells(2).Value
    End If

    If max_tmp < dataGridView1.Rows(i).Cells(2).Value Then
        max_tmp = dataGridView1.Rows(i).Cells(2).Value
    End If

    If min_tmp > dataGridView1.Rows(i).Cells(2).Value Then
        min_tmp = dataGridView1.Rows(i).Cells(2).Value
    End If

Next

avg_tmp = sum_tmp / dataGridView1.Rows.Count()

以上是获取价值的代码。我尝试使用通过选择组合框来改变的整数变量,但仍然总是在min上得到0值。可悲的是,它平均显示出正确的价值。怎么可能错了?

1 个答案:

答案 0 :(得分:0)

您可以使用LINQ表达式获取要处理的值的可枚举集合,然后使用内置函数获取最大值,最小值和平均值

定义一个结构,用于保存结果计算

data[action.key]

此函数在调用时返回结构。传入第一行索引和最后一行索引。

Private Structure ResultsStruct
    Public Min As Single
    Public Max As Single
    Public Average As Single
    Public Sum As Single
End Structure

如何称呼

Private Function getResults(firstRow As Integer, lastRow As Integer) As ResultsStruct
    Dim skipRows = firstRow - 1
    Dim takeRows = lastRow - skipRows
    Dim values = DataGridView1.Rows.
        OfType(Of DataGridViewRow)().
        Select(Of Single)(Function(r) Single.Parse(r.Cells(0).Value.ToString())).
        Skip(skipRows).
        Take(takeRows)
    Dim max = values.Max()
    Dim min = values.Min()
    Dim avg = values.Average()
    Dim result As New ResultsStruct() With {.Max = values.Max(),
                                            .Min = values.Min(),
                                            .Average = values.Average(),
                                            .Sum = values.Sum()}
    Return result
End Function

将示例中的Dim result = getResults(firstRow:=201, lastRow:=300) MessageBox.Show(String.Format("Max: {0}, Min: {1}, Avg: {2}, Sum: {3}", result.Max, result.Min, result.Average, result.Sum)) 201替换为您感兴趣的范围,无论是来自用户选择网格还是其他一些输入方式。