我有一个对象数组,称为用于保存项目GUID列表及其数量的订单。
Dim orders As Object(,) = {{"ItemA", 11}, {"ItemB", 10}, {"ItemA", 2}, {"ItemB", 1}}
我想将其转换为以下内容:
Dim orders As Object(,) = {{"ItemA", 13}, {"ItemB", 11}}
换句话说,我希望有一个明确的项目选择,其中包含该项目的记录总数。 我可以用LINQ做这个,还是应该只使用for循环?
答案 0 :(得分:1)
您可以使用Dictionary(Of TKey, TValue)
按GUID分组
Dim orders As Object(,) = {{"ItemA", 11}, {"ItemB", 10}, {"ItemA", 2}, {"ItemB", 1}}
Dim ordersSum As New Dictionary(Of String, Int32)()
For orderIndex As Int32 = 0 To orders.GetUpperBound(0)
If ordersSum.ContainsKey(orders(orderIndex, 0)) = True Then
ordersSum(orders(orderIndex, 0)) += orders(orderIndex, 1)
Else
ordersSum.Add(orders(orderIndex, 0), orders(orderIndex, 1))
End If
Next
然后如果Dictionary
类型不被允许,你真的需要一个多维数组作为返回类型
Dim result As Object(,) = New Object(ordersSum.Count - 1, 1) {}
Dim index As Int32 = 0
For Each key As String In ordersSum.Keys
result(index, 0) = key
result(index, 1) = ordersSum(key)
index += 1
Next