Vb.net 不确定如何解释datagridview中项目的组和计数列表
假设我有一个DataGridView,其中包含以下数据:Vb.net 不确定如何解释datagridview中项目的组和计数列表,vb.net,datagridview,Vb.net,Datagridview,假设我有一个DataGridView,其中包含以下数据: item1 item1 item2 item2 item2 item2 item3 我应该从哪个方向根据该数据创建这样的列表: 2 x item1 4 x item2 1 x item3 它基本上是说一个项目在列表中出现了多少次,并显示了次数和项目名称 读取第1行“item1”创建计数器,读取列表中的每个项目,当字符串与增量计数器匹配时,转到下一个项目跳过已计数的项目 到目前为止,这就是我所拥有的,但它似乎有点过于复杂。有没有更有效的
item1
item1
item2
item2
item2
item2
item3
我应该从哪个方向根据该数据创建这样的列表:
2 x item1
4 x item2
1 x item3
它基本上是说一个项目在列表中出现了多少次,并显示了次数和项目名称
读取第1行“item1”创建计数器,读取列表中的每个项目,当字符串与增量计数器匹配时,转到下一个项目跳过已计数的项目
到目前为止,这就是我所拥有的,但它似乎有点过于复杂。有没有更有效的方法
Dim counter = 0
Dim listbox As New ListBox 'to store items already scanned
listbox.Items.Clear() 'clear it on each new call
listbox.Items.Add("Test") ' add a dummy value to start the loop
For Each row In DataGridView1.Rows 'check each item in the datagridview
Dim ItemName = row.Cells(1).Value 'declare the initial itemName
Dim flag = True'set the continue bool to true
For Each LoggedItem In listbox.Items 'check each item in the listbox to see if it has been check already
If LoggedItem = ItemName Then
flag = False 'if the item has been checked set the continue bool flag to false to prevent it from adding and displaying the item again
End If
Next 'check next item in listbox
If flag Then
counter = 0 'reset item counter
For Each row2 In DataGridView1.Rows
Dim ItemName2 = row2.Cells(1).Value
If ItemName = ItemName2 Then
counter += 1 'checks each item in the datagridview again and counts how many matches it finds
End If
Next
listbox.Items.Add(ItemName) 'add scanned item to the already checked list
MsgBox(counter & " x " & ItemName) 'display item totals
End If
flag = True 'reset flag for next item
Next 'continuum to next item
如果您使用一点linq,您可以在一行中完成大部分工作。通过使用linq分组可枚举集合,您可以获得不同的值列表及其计数,然后根据需要输出结果。下面是一个winforms示例,您可以将其粘贴到新项目中以开始: 用于设置测试的代码: 获取不同的值及其计数:
在我们创建
column1GroupedValues
的地方,神奇的一切都会发生。我们告诉linq获取每行中第一个单元格的值,然后将它们分组。一旦您拥有了该集合,您就可以访问每个条目的键
和计数
属性,您可以以任何方式显示这些属性。这里有一个很好的lamba函数。一行代码:可能首先需要一个不同项目的列表,并使用它来迭代计数?我将不得不检查它,如果你的意思是一个不同项目的列表作为预定义的项目列表,那么我将无法生成它,因为列表中的数据每次都会更改谢谢
'Create DataGridView and add it to the form
Dim dgv As New DataGridView With {
.Location = New Point(50, 50),
.Size = New Size(150, 300),
.AllowUserToAddRows = False
}
dgv.Columns.Add("Column1", "Column 1")
Me.Controls.Add(dgv)
'Put some test data in it
Dim testValues As String() = {"item1", "item1", "item2", "item2", "item2", "item2", "item3"}
For Each testValue As String In testValues
dgv.Rows.Add(New String() {testValue})
Next
'Now to the question at hand...
Dim column1GroupedValues = dgv.Rows.OfType(Of DataGridViewRow).Select(Function(row) row.Cells(0).Value.ToString()).GroupBy(Function(x) x)
Dim outputString As New System.Text.StringBuilder
For Each grpVal In column1GroupedValues
outputString.Append(String.Format("{0} x {1}" & vbCrLf, grpVal.Count.ToString, grpVal.Key))
Next
MsgBox(outputString.ToString)
'Outputs:
'2 x item1
'4 x item2
'1 x item3