0

I have a dictionary that contains a random amount of variables (differs depending on the document it's scanning) in the following format

  • ,A, 500
  • ,ORD, 50000
  • ,ORD, 200

I need to be able to group together all of the values that belong to the same class (ORD being one and A being another) and then add the integers together so that I can output

A - 500

ORD - 50200

So I think I need to assign different integer variables depending on the amount of classes and then add them together but I really don't know how to go about it

EDIT to insert code:

Dim sharenum As Int32 = 0
Dim tempshold As String = ""
  For Each sHolder In shareholders
        tempshold = Replace(sHolder.numberShares, ",", "")
        sharenum = Convert.ToInt32(tempshold)
        dicClassShares.Add("," & Trim(sHolder.shareClass) & ",", sharenum)
Sam Axe
  • 33,313
  • 9
  • 55
  • 89
  • Show code where you initialize your dictionary. Is `"ORD"` and `"A"` are the keys of dictionary? – Fabio Sep 13 '17 at 06:40
  • Sorry, added as an edit – Chris Dews Sep 13 '17 at 06:57
  • 2
    I wonder why you don't get an error "Key already exists" when you add `,ORD` as key to the dictionary. – muffi Sep 13 '17 at 06:59
  • If `dicClassShares` is of type `Dictionary` your code will throw exception for duplicated `sHolder.shareClass` – Fabio Sep 13 '17 at 07:00
  • I'm just curious, if `dicClassShare` is dictionary, it will not able to have duplicate key. Or you want to update the value if the key already exists? If yes, [this question](https://stackoverflow.com/questions/4245064/method-to-add-new-or-update-existing-item-in-dictionary) did answer your question – Prisoner Sep 13 '17 at 07:01

1 Answers1

0

Change your dictionary structure to a Dictionary(Of String, List(Of Int32))

Then check for the key and either add or edit the dictionary entry depending on the presence of the key:

Dim dicClassShares As Dictionary(Of String, List(Of Int32)) = New Dictionary(Of String, List(Of Int32))

If Not dicClassShares.ContainsKey Then
    dicClassShares.Add("," & Trim(sHolder.shareClass) & ",", New List(Of Int32))
End If
dicClassShares("," & Trim(sHolder.shareClass) & ",").Add(sharenum)

And finally obtain the summed value you want...

Dim summedValues As Dictionary(Of String, Int32) = 
    dicClassShares.ToDictionary(Of String, Int32)(
        Function(k) k.Key,
        Function(v) v.Value.Sum
    )

That last bit is off the top of my head. Play around with it if you get errors.

Sam Axe
  • 33,313
  • 9
  • 55
  • 89