Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Array.FindAll

Status
Not open for further replies.

DarkConsultant

Programmer
Dec 4, 2007
156
GB
Hi,

I have an array full of strings and I need to extract numbers of instances.

E.G.
Dim MyArray() as String = ("apple","banana","cat","apple")

How do I find out how many apples or banana's etc.

I currently iterate over the array and count them but Array.FindAll should work. I am having difficulty understanding the predicate function to return values although I use predicates in other parts of my code without a problem. If i want to return everything that starts with 'a' no problem I use a predicate that checks StartsWith("a") but I just need the quantity.

I am sure I am missing something so can anyone fill in the blanks?


DarkConsultant

Live long and prosper \\//
 
Use the Filter function:

Dim MyArray(3) As String

myArray(0) = "apple"
myArray(1) = "banana"
myArray(2) = "cat"
myArray(3) = "apple"

Dim FilteredArray() As String

FilteredArray = Filter(MyArray, "apple")

MsgBox(FilteredArray.Length)

FilteredArray = Filter(MyArray, "banana")

MsgBox(FilteredArray.Length)

FilteredArray = Filter(MyArray, "cat")

MsgBox(FilteredArray.Length)


I used to rock and roll every night and party every day. Then it was every other day. Now I'm lucky if I can find 30 minutes a week in which to get funky. - Homer Simpson

Arrrr, mateys! Ye needs ta be preparin' yerselves fer Talk Like a Pirate Day!
 
You can also try this.....

Dim MyArray() As String = New String() {"apple", "banana", "cat", "apple"}

'Sub routine to get the occurances/count of the strings
'in your array

Sub findOccurances()
Dim appleCount, bananaCount As Integer

For Each str As String In MyArray
Select Case str
Case "apple"
appleCount += 1
Case "banana"
bananaCount += 1

End Select
Next

MessageBox.Show("There are " & appleCount & " Apples and " & bananaCount & " banana")
End Sub
 
Hi All,

Ju5t1c3, thanks man that's the same solution I found.

jebensen, Filter, FILTER! HOW DID I NOT KNOW ABOUT THAT! Sometimes I dispair I really do ... thanks mate that is exactly what I was looking for.

jebensen 4 president.

Thanks everyone.

DarkConsultant

Live long and prosper \\//
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top