vb.net 4.0中字典的求和整数值字段

时间:2012-01-06 12:31:44

标签: .net vb.net dictionary

在.net 4.0词典中我知道我可以像这样计算所有整数值字段的总和:

 Dim dbar As Dictionary(Of String, Integer) = New Dictionary(Of String, Integer)() From {{"A", 1}, {"B", 1}, {"C", 1}}
    Dim sum As Integer = 0
    For Each v As Integer In dbar.Values
      sum += v
    Next

是否存在更优雅的方式来计算总和?

2 个答案:

答案 0 :(得分:8)

只需使用Sum()方法:

dbar.Values.Sum()

答案 1 :(得分:3)

是的,使用LINQ to Objects:

Dim sum As Integer = dbar.Values.Sum()