3

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

4
  • So you don't want to use LINQ or a for loop. What are you looking for? Could you provide a sample output? Commented Feb 20, 2013 at 18:56
  • 2
    Dim count = itemlist.Where(Function(s) s = "VALUE1").Count Commented Feb 20, 2013 at 19:00
  • I could use linq, I just figured there would be a simple way using lists to count duplicates. For example, if my list contained "RED", "RED", "RED", "GREEN", It would output RED - 3, GREEN - 1 Commented Feb 20, 2013 at 19:12
  • There is a simple way, use LINQ ;-) Commented Feb 20, 2013 at 19:12

1 Answer 1

8

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I intend however to populate based on whats occuring in the list. For example, Lets say my list generates "RED", "RED", "RED", "BLUE". I want to display the occurence value as "RED" - 3, "BLUE" - 1. But what if "GREEN" shows up in the list? I would like to just populate each uniquely and then count the duplicates instead of searching for a set value

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.