如何获得每10行的值的总和?

时间:2018-10-24 15:36:31

标签: vb.net

在Datagridview中有一列(超过300行),并且想要获取每10行的总和。列1中的数据之间没有间隙。

我只想在另一列中获得每10行的总和值。我尝试向我显示每行中的累积编号!

任何帮助将不胜感激。非常感谢!

C1 C2

2
3
4
6
5
3
5
7
6
5 46

8
9
4
7
5
2
1
2
5
4 47

1
2
6


Dim sum As integer = 0

For i = 0 To data1.Rows.Count - 1
sum += data1.Rows(i).Cells(0).Value
data1.Rows(i).Cells(1).Value = sum

If (i+1) = 10 Then
Sum = 0
Else
End If

Next

2 个答案:

答案 0 :(得分:1)

有多种方法,下面是一个示例:

遍历每行求和,然后每10个输出求和并重置编号。

    For i = 0 To data1.Rows.Count - 1
        sum += data1(0, i).Value
        If i.ToString.EndsWith("9") Then 'since it starts at 0, 10th ends with 9 not 0
            data1(1, i).Value = sum
            sum = 0
        End If
    Next

答案 1 :(得分:0)

使用LINQ来获取每组n行的总和

Private Function getSumsOfGroupsOfNRows(n As Integer) As IEnumerable(Of Double)
    Return DataGridView1.Rows.OfType(Of DataGridViewRow).
        GroupBy(Function(r) Math.Truncate(r.Index / n)).
        Select(Function(g) g.Sum(Function(r) CDbl(r.Cells(0).Value)))
End Function

对此进行测试

Dim n = 10
' adds numbers 1 through 100 in the datagridview, for testing
DataGridView1.Rows.AddRange(Enumerable.Range(1, 100).Select(
    Function(r)
        Dim row As DataGridViewRow = DataGridView1.Rows(0).Clone
        row.Cells(0).Value = r
        Return row
    End Function).ToArray())
' get the sums in an IEnumerable(Of Double)
Dim sums = getSumsOfGroupsOfNRows(n)
' write into second column
For i = 1 To n
    DataGridView1.Rows.Item(n * i - 1).Cells(1).Value = sums(i - 1)
Next