VB.NET 通过字典进行数据计数/求和
一线编程
发布
于
2019-07-22 15:10:03
发布
于
2019-07-22 15:10:03
字典的计数/求和都是通过利用,字典keys键的唯一性进行统计,当key键出现相同时进行数量的加一或者进行keys键的值求和!
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
DIC_RES(1)
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
DIC_RES(0)
End Sub
Sub DIC_RES(ByVal ST As Integer)
RichTextBox1.Text = "" '清空文本框
'定义二维数组
Dim arr(,) As Object = {{"A", 1}, {"B", 2}, {"P", 3}, {"D", 4}, {"P", 5}, {"A", 6}, {"R", 7}, {"C", 8}, {"D", 9}, {"E", 10}}
'定义一个字典
Dim dic As Dictionary(Of String, String) = New Dictionary(Of String, String)
'遍历数组取数
For i As Integer = 0 To UBound(arr, 1)
If ST = 1 Then '判断状态为1时执行计数否则执行求和
If dic.ContainsKey(arr(i, 0)) Then '判断key是否存在
dic(arr(i, 0)) += 1 '相同加一
dic(arr(i, 0)) = 1 '否则保持唯一
End If
If dic.ContainsKey(arr(i, 0)) Then '判断key是否存在
dic(arr(i, 0)) = dic(arr(i, 0)) + arr(i, 1) '相同的keys值求和
dic(arr(i, 0)) = arr(i, 1) '否则变
End If
End If
For Each ch As String In dic.Keys '遍历取出统计后的数据
If ST = 1 Then
RichTextBox1.AppendText(ch & "出现" & dic(ch) & "次" & vbCrLf)
RichTextBox1.AppendText(ch & "的和为" & dic(ch) & vbCrLf)