vb.net - 如何在datagridview中对相同id的值求和?
问题描述
我正在尝试对 datagridview 中相同 id 的值求和并尝试更新 sql 数据库表。怎么做?
For i As Integer = 0 To DataGridView2.Rows.Count - 1
If Convert.ToInt32(DataGridView2.Rows(i).Cells(0).Value) = Convert.ToInt32(DataGridView2.Rows(i).Cells(0).Value) Then
y += Convert.ToInt32(DataGridView2.Rows(i).Cells(3).Value)
End If
Next
解决方案
您可以使用 Dictionary 使用总和值检查和分组 id
Dim totals As Dictionary(Of String, Integer) = New Dictionary(Of String, Integer)()
For i As Integer = 0 To DataGridView2.Rows.Count - 1
Dim group As String = Convert.ToInt32(DataGridView2.Rows(i).Cells("id").Value)
Dim qty As Integer = Convert.ToInt32(DataGridView2.Rows(i).Cells("value").Value)
If totals.ContainsKey(group) = False Then
totals.Add(group, qty)
Else
totals(group) += qty
End If
Next
或使用 LINQ 组:
Dim totals = DataGridView2.Rows.Cast(Of DataGridViewRow)().GroupBy(Function(row) row.Cells("id").Value.ToString()).[Select](Function(g) New With {Key
.id= g.Key, Key
.SumValues = g.Sum(Function(row) Convert.ToInt32(row.Cells("value").Value))
})
推荐阅读
- jestjs - 如何停止 Jest 在测试输出中包装“console.log”?
- protractor - 如何从量角器中的输入文本字段中散焦光标
- javascript - 为什么每次收到不同的密钥时组件都会重新安装?
- javascript - 如何正确使用箭头函数使此函数输出 {say:"sticks",field:"awoo"}
- r - 如何将日期/时间戳转换为日期变量,以便找出会议需要多长时间?
- android - 这是附加到视图的内存泄漏吗?
- java - 千位精灵绘制性能不佳
- c# - 将应用程序身份验证升级到 Core 2.0+
- android - React Native:指定的孩子已经有一个父母
- node.js - 带有过滤器嵌入文档 NoseJS 的 Mongodb 聚合