Vb.net 向嵌套字典添加值
目前,我正在尝试使用VB将值添加到嵌套字典中。我用它来编写一个简单的字典,但是我不能完全理解它的语法 到目前为止,我已经评论了我遇到问题的几行:Vb.net 向嵌套字典添加值,vb.net,reporting-services,Vb.net,Reporting Services,目前,我正在尝试使用VB将值添加到嵌套字典中。我用它来编写一个简单的字典,但是我不能完全理解它的语法 到目前为止,我已经评论了我遇到问题的几行: Public Shared Dim dictionary AS New System.Collections.Generic.Dictionary(Of String, System.Collections.Generic.Dictionary(Of String, Integer)) Function addValue(ByVal code AS
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
我想做的是让字典的结构如下:
Code1:
Customer1: 12
Customer2: 13
Code 2:
Customer1: 12
Customer2: 13
下面是一个函数,它将执行您想要的操作 它所做的第一件事是检查
字典
中是否存在code
的条目。如果不存在,它将添加一个值为空字典的字典,该字典将接收cust
-value
对
当前该函数不返回任何值。如果不返回任何值,则应使用子项
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
这似乎在做我希望它做的事情,但是我如何访问内部字典中的值呢?如下所示:
dictionary(code).Item(cust)
我还需要将与代码关联的值和customer@Ualati我添加了一个函数来对客户的值求和。是的,要访问内部字典,您可以使用字典(code).项目(cust)
或字典(code)(cust)
,但您需要检查code
和cust
条目是否存在,否则会引发异常。我没有意识到在第一个函数中添加了单个客户条目,这很好,但我把字典当作一个总的数字。(我知道这并不理想,但SSRS在获取总数方面有着奇怪的规则)在我的字典版本中,没有嵌套,每次添加新的字典时,我都有下面的代码来更新值IF dictionary.ContainsKey(cust)Then dictionary(cust)=dictionary.Item(cust)+value Else dictionary.Add(cust,value)End IF
我的“解决方案”是这样做IF Not dictionary.ContainsKey(code)Then dictionary.Add(code,New System.Collections.Generic.dictionary(字符串,整数))Else If dictionary(code).ContainsKey(cust)Then dictionary(code)(cust)=dictionary(code).Item(cust)+value End If End If End If End If