在vb.net的对象列表中查找重复项并合并它们的简化方法
我有一个API,它接受objectsObject包含ProductID和Quantity的列表。我想确定传递的列表上是否有重复的产品ID。如果发现重复项,我将通过添加重复产品ID的数量来合并它们。为此,我创建了自己的算法,一个接一个地循环列表,然后将其存储到另一个经过验证的列表中。代码是这样的在vb.net的对象列表中查找重复项并合并它们的简化方法,vb.net,Vb.net,我有一个API,它接受objectsObject包含ProductID和Quantity的列表。我想确定传递的列表上是否有重复的产品ID。如果发现重复项,我将通过添加重复产品ID的数量来合并它们。为此,我创建了自己的算法,一个接一个地循环列表,然后将其存储到另一个经过验证的列表中。代码是这样的 For Each passedVoucher As VoucherInfo In VouchersToRelease indexofduplicate = 0 sumQuantity
For Each passedVoucher As VoucherInfo In VouchersToRelease
indexofduplicate = 0
sumQuantity = 0
hasDuplicate = False
If VerifiedReleasedVouchers.Count() > 0 Then
'for loop that checks if productID exists in the VerifiedReleasedVouchers
For Each finalList As VoucherInfo In VerifiedReleasedVouchers
If passedVoucher.ProductID = finalList.ProductID Then
indexofduplicate = VerifiedReleasedVouchers.IndexOf(finalList)
'if true, adds the Quantity of duplicate to the existing quantity at the VerifiedReleasedVouchers
sumQuantity = Convert.ToInt32(VerifiedReleasedVouchers(indexofduplicate).Quantity) + Convert.ToInt32(passedVoucher.Quantity)
VerifiedReleasedVouchers(indexofduplicate).Quantity = sumQuantity.ToString
hasDuplicate = True
Exit For
End If
Next
End If
'adds the voucher to verified released voucher if no duplicate was found
If hasDuplicate = False Then
VerifiedReleasedVouchers.Add(passedVoucher)
End If
Next
所以我所做的是,我ForEach循环了通过的列表。在循环中,我将passedList中的当前对象与verifiedListw/c中的每个对象进行了比较,以确定它们是否是重复的产品ID。如果没有找到重复的,我将只将当前对象添加到verifiedList中。如果发现重复,我只需通过存储两个对象的数量之和,从具有相同ProductID的已验证列表中更新该对象
上面的代码完全按照预期工作,但问题是,它执行了很多任务。有什么方法可以简化我上面所做的吗
p.S.List.Distinct不是解决此问题的解决方案您可以使用Linq轻松实现您想要的。首先,您必须按ProductID分组,然后选择数量总和为的所有组。最后,我们得到一个列表:
Dim VerifiedReleasedVouchers As List(Of VoucherInfo) = VouchersToRelease.GroupBy(Function(x) x.ProductID).[Select](Function(y) New VoucherInfo() With {
.ProductID = y.Key,
.Quantity = y.Sum(Function(z) z.Quantity),
.Denom = y.First().Denom
}).ToList()
如果你想要有数量的唯一项目编号,我的第一个想法是:尝试使用字典,它应该完全适合你的需要。你也可以使用Linq:use GroupBy IDT感谢老兄,它对我有用。但我有一个问题。我的VoucherInfo中还有一个名为Denom的字段,我有ProductID、Denom和Quantity。我怎样才能保留我通过的列表的原始名称?嗯,这要看情况而定。对于同一个产品ID,Denom总是一样的吗?是的。在合并过程中,我唯一修改的是数量,然后您可以将.Denom=y.First.Denom添加到所选部分,在.Quantity=y.SumFunctionz z.Quantity之后,我已经编辑了我的答案