Get the sum of distinguishable values โ€‹โ€‹from a list in VB.Net

I have a list named Cart_Items and it populates when the Add to Cart button is clicked. The list contains the ItemID and Quantity objects. I need to get the total number of items from this list. Since there are different items in the list, I cannot get the total of a specific item. if i use sum (function) it returns the sum of all values. And what I'm trying to achieve is that if there is more than one record of the same item then get the SUM of that number of a specific item. here is the class structure:

Public Class CartItem
Private m_ItemId As Integer
Public Property ItemId() As Integer
    Get
        Return m_ItemId
    End Get
    Set(value As Integer)
        m_ItemId = value
    End Set
End Property

Private m_Quantity As Integer
Public Property Quantity() As Integer
    Get
        Return m_Quantity
    End Get
    Set(value As Integer)
        m_Quantity = Value
    End Set
End Property
End Class

      

List:

ItemId      Quantity
1            5
3            6
1            2
1            6
4            8

      

so I want to get the total ItemId = 1, which should be 13.

So what would be the best way to get the total for a specific itemId? Thank.

+3


source to share


2 answers


First, filter the items with a given criterion, which in this case CartItems

has itemId

of 1

. Then select all values โ€‹โ€‹and apply distinct

to remove duplicate values โ€‹โ€‹and finally the sum

result.



Dim result As Integer = (From item In myList
                         Where item.ItemId = 1
                         Select item.Quantity).Distinct().Sum()

      

+2


source


You need to collect all the elements according to them Id

, calculate the amount Quantity

for each group.

var itemTotals = myList.GroupBy(Function(item) item.ItemId)
                       .Select(Function(group)
                                  Return New With
                                  {
                                      .ItemId = group.Key,
                                      .Quantity = group.Sum(Function(item) item.Quantity)
                                  }
                               End Function)
                       .ToList()

      

So, you will get a collection of anonymous objects with all the elements in myList

and their sums.



{ .ItemId = 1, Quantity = 13 }
{ .ItemId = 3, Quantity = 6 }
{ .ItemId = 4, Quantity = 8 }

      

Instead of anonymous types, you can use your class CartItem

because it has the same properties in the same context. Therefore, Select

pert will look like this:

.Select(Function(group)
            Return New CartItem With
            {
                .ItemId = group.Key,
                .Quantity = group.Sum(Function(item) item.Quantity)
            }
        End Function)

      

0


source







All Articles