遍历 Cart GroupBy 和 Sum

Iterate through Cart GroupBy and Sum

我需要遍历购物车,按代码和日期分组,然后对匹配相同代码和日期的整数求和。不确定 LINQ 是否会在这里提供帮助。如果更容易避免 LINQ,那就太好了。

这是我的 Class:

Class CartProduct

  Property ActCode As String
  Property Customers As Integer
  Property Date As Date 

End Class

这是我的函数:

Function GetTotals() As IEnumerable(Of String)

Dim totalList As New List(Of String)

   For Each p As CartProduct In _products

     totalList.Add(p.ActCode)
     totalList.Add(p.Customers)
     totalList.Add(p.Date)       

   Next

   Dim result = From newList In totalList
                Group by totalList.ActCode and totalList.Date
                Sum totalList.Customers ??? 
                Select newList {}

   Return result

End Function

这是 _products returns:

 Friend Property Products As List(Of CartProduct)
    Get
        Return _products
    End Get
    Set(value As List(Of CartProduct))
        _products = value
    End Set
End Property

我无法访问 CartProduct 属性以在新列表中进行分组。这就是让我绊倒的原因。

编辑:希望这能让我和其他人朝着富有成效的方向前进。 How to sum similar element of an array of structure in vb.net?

谢谢。

如果要对 CartProduct 中的字段进行分组和求和,则只需直接使用 CartProduct 列表即可:

Function GetTotals() As IEnumerable(Of String)
    Dim result = From p In _products
                 Group By p.ActCode, p.Date Into Sum(p.Customers)

   Return result
End Function