Count repeated items in a listbox

0

I have a listbox with a series of elements and I would like to know the code to find the times that an element repeats, for example:

producto A
producto A
producto A
producto A
producto B
producto B

save in variables that the frequency of A is 4 and the frequency of B is 2.

    
asked by Edgar Cardenas 10.05.2017 в 16:50
source

1 answer

2

From the listbox items you can get a collection of strings with the different elements.

From there you can get the different values and the number of occurrences by making a GroupBy with LINQ:

    Dim items = ListBox1.Items.Cast(Of String)
    Dim totales = items.GroupBy((Function(i) i)) _
        .Select(Function(g) new KeyValuePair(Of String, Integer)(g.Key, g.Count()))
    For Each item As KeyValuePair(Of String,Integer) In totales
        Debug.WriteLine($"{item.Key}: {item.Value}")
    Next
    
answered by 10.05.2017 в 17:40