Reputation: 1834
I have an API that accepts a list of objects(Object contains ProductID and Quantity). I want to determine whether there are duplicate product ID on the passed list. If duplicates are found, I'll merge them by adding the Quantity of duplicate product ID. To do this, I created my own algorithm that loops the list one-by-one then store it to another list (the verified one). The code goes like this.
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
So what I did is, I ForEach looped the passed list. Inside the loop, I compared the current object from the passedList into every object in the verifiedList(w/c is empty by default) to determine whether their are duplicate product ID. If no duplicate was found, i'll just add the current object to the verifiedList. If duplicate was found, ill just update the object from the verified list with the same ProductID by storing the sum of the Quantity of both objects.
The code above works perfectly as intended but the thing is, it performs a lot of tasks. Is there any way to simplify what I did above?
P.S. List.Distinct() is not a solution for this
Upvotes: 0
Views: 858
Reputation: 7713
You could use Linq to easily achieve what you want. First you must GroupBy
ProductID and then Select
all the groups with a sum of the quantity. Finally, we get a list:
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()
Upvotes: 1