Community discussion forum

Finding the number of elements that match a string in VB.NET Array's

  • 1 year ago
    Hi, If I have a string array of various words (apple, carrot etc) and I need to know how many elements are carrot or how many apples I have what is the best method. I use a loop at the moment but there must be a better way. Any ideas?
  • 1 year ago
    Hi David, Great to see you again on the forums :) How does your loop look at the moment? You'd probably need to just tally up each item as you iterate through the list, so something like this: Dim wordCounts As New Dictionary(Of String, Integer)() For Each word As String In wordArray     If wordCounts.HasKey(word) Then         wordCounts(word) += 1     Else         wordCounts(word) = 0     End If Next (please forgive any syntax errors.. but hopefully you get the idea) If you're using .NET 3.5 then there are more options... and probably use the ToLookup() method to get the totals that way. Hope that helps
  • 1 year ago
    *and for normal array* Function CountElements(a As String(), counted() as string) as Integer() dim Ret(counted.getUpperBound(0) As Integer for c as integer = 0 to counted.GetUpperdbound(0) for e As integer = 0 to a.getUpperbound(0) if a(e)=counted(c) then ret(c)+=1 ... return ret

Post a reply

Enter your message below

Sign in or Join us (it's free).

We'd love to hear what you think! Submit ideas or give us feedback