【问题标题】:Iterate through Cart GroupBy and Sum遍历购物车 GroupBy 和 Sum
【发布时间】:2018-02-26 19:58:23
【问题描述】:

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

这是我的班级:

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 返回的内容:

 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?

谢谢。

【问题讨论】:

  • 如何将DateInteger 添加到List(Of String) 中?这段代码能编译吗? _products的类型是什么?
  • 如果我只想返回totalList,它编译得很好。购物车包含带有字符串、日期和整数的产品。多个产品可以有不同的字符串、日期和整数。
  • 当我尝试时,我发现你不能使用Date 作为属性名称,但我忘记了VB 可能会自动将其他类型转换为string。在这种情况下,这没有帮助。
  • 感谢您的回复。我已经编辑了我的原始帖子以包含 _products 的实际含义。

标签: arrays vb.net linq ienumerable


【解决方案1】:

如果您想对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

【讨论】:

  • 谢谢@NetMage。我知道这是我没有想到的愚蠢的事情。我不知道我不需要使用 For Each 来遍历 CartProducts。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多