我有一个需要削减的对象列表。这些项目是可变的,所以我不能强行它。
这是我想要做的......
原始对象列表......
"Name":"Apple","Qty":1 "Name":"Banana","Qty":2 "Name":"Apple","Qty":3 "Name":"Banana","Qty":4 "Name":"Strawberry","Qty":5
削减后的对象列表......
"Name":"Apple","Qty":4 "Name":"Banana","Qty":6 "Name":"Strawberry","Qty":5
我在.net 4.5环境中工作,所以我对任何方法都持开放态度。
答案 0 :(得分:0)
所以你有一个具有Name和Qty属性的对象列表?您可以使用group by和aggregate:
var items = list _
.GroupBy(Function(i) i.Name) _
.Select(Function(i) new Item With { .Name = i.Key, .Qty = i.Sum(Function(q) q.Qty) })
按名称分组,然后您可以使用Sum汇总项目总数。你也可以从another example看到这个。
答案 1 :(得分:0)
您可以查看创建一个字典,该字典将名称存储为键,然后编号为值:
Private _dict As Dictionary(Of String, Integer)
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
_dict = New Dictionary(Of String, Integer)
AddToDictionary("Apple", 1)
AddToDictionary("Banana", 2)
AddToDictionary("Apple", 3)
AddToDictionary("Banana", 4)
AddToDictionary("Strawberry", 5)
'The following outputs:
'Apple : 4
'Banana : 6
'Strawberry : 5
For Each kvp In _dict
Debug.WriteLine(kvp.Key & " : " & kvp.Value)
Next
End Sub
Private Sub AddToDictionary(name As String, value As Integer)
If _dict.ContainsKey(name) Then
_dict(name) += value
Else
_dict.Add(name, value)
End If
End Sub