Jason Bayldon
Jason Bayldon

Reputation: 1296

How to count string occurences in a list(Of String)

I am looking to dynamically count from a list, how many times items have occured. I can do it below if I specify the value I am looking for, but what I am really looking to do is to iterate through my list, count occurences, and total them out. My current code is below:

Dim itemlist As New List(Of String)
itemlist.add("VALUE1")
itemlist.add("VALUE2")
itemlist.add("VALUE3")


    Dim count As Integer = 0

    For Each value In itemlist

        If value.Equals("VALUE1") Then count += 1

    Next

 Msgbox(count.tostring)

So my point would be instead of searching for the value, let the app total them up and display the counted occurences it to the user, similar to a "COUNTIF" in excel. I cant find much on this without using LINQ, Thanks

Upvotes: 3

Views: 12553

Answers (1)

Meta-Knight
Meta-Knight

Reputation: 17875

You can do this very easily with LINQ:

Msgbox(itemlist.Where(Function(value) value = "VALUE1").Count)

To count duplicates, once again it's easy with LINQ:

Dim itemlist As New List(Of String)
itemlist.Add("RED")
itemlist.Add("RED")
itemlist.Add("RED")
itemlist.Add("GREEN")

dim groups = itemList.GroupBy(Function(value) value)

For Each grp In groups
    Console.WriteLine(grp(0) & " - " & grp.Count )
Next

Output:

RED - 3
GREEN - 1

Upvotes: 8

Related Questions