VB.net - grouping identical values then manipulating the result

Tags: vb.net
By : Rocks
Source: Stackoverflow.com
Question!

I have found some similar questions but none that hit what I am looking for. Lets say I have an array of 10 values for fruit :

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) = ""

now, i have a statement that says that fruit(6)="apple", making the array :

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) = ""

I want to have a sub that will group like items and only store it once. So,

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) = "" 

and then next time i add an apple it goes to "3 x apple" and so on.

so in pseudo code i want it to

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

what's the simplest and most elegant way to do this in vb.net? is there a way to do it without LINQ?

By : Rocks


Answers

@the_lotus is right, you can use a dictionary

   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

And then return

   Function NumberOfFruit(fruitname As String) As String
      Return fruits.Item(fruitname) 
By : Ben238


This video can help you solving your question :)
By: admin