Currently I'm trying to add values into a nested dictionary using VB. I have it working for a flat dictionary, but can't quite get my head around the syntax for doing it nested.
What I have so far is, I have commented the lines I'm having trouble with:
Public Shared Dim dictionary AS New System.Collections.Generic.Dictionary(Of String, System.Collections.Generic.Dictionary(Of String, Integer))
Function addValue(ByVal code AS String, ByVal cust AS String,ByVal value AS Integer)
Dim innerDict AS New System.Collections.Generic.Dictionary(Of String, Integer)
innerDict.Add(cust,value);
IF dictionary.ContainsKey(code) Then
IF dictionary.Item(code).ContainsKey(cust) Then 'Can I access the Customer key in this way?
dictionary.Item(code).Item 'Here I need to update the value held by customer to the old value + new value.
Else
dictionary(code).Add(cust,value) 'Is this syntax correct?
End If
Else
dictionary.Add(code,innerDict)
End If
End Function
What I want to happen is to have a dictionary structured as follow:
Code1:
Customer1: 12
Customer2: 13
Code 2:
Customer1: 12
Customer2: 13
Here is the function that will do what you want.
The first thing it does, is checks whether an entry exists for code
in dictionary
. If none exists, it adds one whose value is an empty dictionary that will receive the cust
-value
pairs.
Currently the function does not return any value. If no value is to be returned, you should use a Sub
.
Function addValue(ByVal code As String, ByVal cust As String, ByVal value As Integer)
' If no entry for code, create one.
If Not dictionary.ContainsKey(code) Then
dictionary.Add(code, New System.Collections.Generic.Dictionary(Of String, Integer))
End If
' Add cust, value to entry at code.
dictionary(code).Add(cust, value)
End Function
' Returns sum the customer's values.
Function SumCustomerValues(customer As String) As Integer
Dim sum As Integer = 0
For Each d As KeyValuePair(Of String, System.Collections.Generic.Dictionary(Of String, Integer)) In dictionary
If d.Value.ContainsKey(customer) Then
sum += d.Value(customer)
End If
Next
Return sum
End Function
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments