获得计数的逻辑很容易,但在实践中有时会变得困难。
现在,我有一个包含许多项目的列表。如果重复出现该如何计数那些项目,我想使用FOR循环将其转换为数字,因为我知道列表中有多少项目。
我尝试了一些代码,但没有成功
'''''''''''''''
' VB 2015
''''''''''''
Public Class Form1
Private Sub lstWinners_List_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstWinners_List.SelectedIndexChanged
If lstWinners_List.SelectedIndex <> -1 Then
Dim count As Integer = 0
Dim strselection As String = lstWinners_List.Items(lstWinners_List.SelectedIndex).ToString
For i As Integer = 0 To lstWinners_List.Items.Count - 1
If lstWinners_List.Items(i) = strselection Then
count = count + 1
End If
Next
lblOutput.Text = count.ToString
End If
End Sub
End Class
对于EX: 我想通过单击它来数数“密歇根”一词在列表中重复多少次?
答案 0 :(得分:1)
这是一个使用吉姆·休伊特(Jim Hewitt)评论的示例:
Private Sub lstWinners_List_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstWinners_List.SelectedIndexChanged
If lstWinners_List.SelectedIndex <> -1 Then
Dim selection As String = lstWinners_List.Items(lstWinners_List.SelectedIndex).ToString
Dim wins As Integer = (From team As String In lstWinners_List.Items Where team.Equals(selection)).Count
lblOutput.Text = wins.ToString
End If
End Sub
修改
这是一本等效的手册,为循环编入了索引:
Private Sub lstWinners_List_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstWinners_List.SelectedIndexChanged
If lstWinners_List.SelectedIndex <> -1 Then
Dim count As Integer = 0
Dim selection As String = lstWinners_List.Items(lstWinners_List.SelectedIndex).ToString
For i As Integer = 0 To lstWinners_List.Items.Count - 1
If lstWinners_List.Items(i) = selection Then
count = count + 1
End If
Next
lblOutput.Text = count.ToString
End If
End Sub
答案 1 :(得分:0)