2016-09-07 61 views
0

我發現了一些類似的問題,但沒有找到我想要的東西。可以說我有10個值的水果的數組:VB.net - 將相同的值分組,然後操縱結果

fruit(1) = "apple" 
fruit(2) = "orange" 
fruit(3) = "banana" 
fruit(4) = "cherry" 
fruit(5) = "peach" 
fruit(6) = "" 
fruit(7) = "" 
fruit(8) = "" 
fruit(9) = "" 
fruit(10) = "" 

現在,我有說,水果(6)=「蘋果」,使得陣列聲明:

fruit(1) = "apple" 
fruit(2) = "orange" 
fruit(3) = "banana" 
fruit(4) = "cherry" 
fruit(5) = "peach" 
fruit(6) = "apple" 
fruit(7) = "" 
fruit(8) = "" 
fruit(9) = "" 
fruit(10) = "" 

我想有一個分組,像物品一樣只存儲一次。所以,

fruit(1) = "2 x apple" 
fruit(2) = "orange" 
fruit(3) = "banana" 
fruit(4) = "cherry" 
fruit(5) = "peach" 
fruit(6) = "" 
fruit(7) = "" 
fruit(8) = "" 
fruit(9) = "" 
fruit(10) = "" 

然後下次我添加一個蘋果它會去「3 x蘋果」等。

所以在僞代碼中,我希望它

look for duplicate values 
count how many duplicates 
alter the original item 
delete all but the newly altered entry 

什麼是在vb.net做這個最簡單,最優雅的方式?有沒有辦法做到這一點沒有LINQ?

+4

你可以使用詞典(字符串,整數),其中的關鍵是水果和值是伯爵。只要檢查密鑰是否已經存在,如果是,則增加計數。順便說一句,數組從索引0開始不是1. –

+0

@the_lotus根據你聲明數組的方式,你可以使用VB.NET在1或0處索引數組 - 取決於你如何聲明數組 - 如果你的Dim水果(10)As Integer '你會得到一個從'fruit(0)'到'fruit(10)'的數組,儘管它與.NET的其他部分保持一致可能是最好的。 –

回答

0

@the_lotus是正確的,你可以使用字典

Dim fruits As New Dictionary(Of String, Integer) 

    Sub AddFruit(fruitname As String) 
     If fruits.ContainsKey(fruitname) Then 
     fruits.Item(fruitname) += 1 
     Else 
     fruits.Add(fruitname, 1) 
     End If 
    End Sub 

然後返回

Function NumberOfFruit(fruitname As String) As String 
     Return fruits.Item(fruitname) & " x " & fruitname 
    End Function