gpt4 book ai didi

vb.net - 从 VB.Net 列表中获取不同值的总和

转载 作者:行者123 更新时间:2023-12-02 05:19:27 24 4
gpt4 key购买 nike

我有一个名为 Cart_Items 的列表,当用户按“添加到购物车”按钮时会填充该列表。该列表包含对象 ItemID 和 Quantity。我需要从此列表中获取商品的总数量。由于列表中有不同的项目,我无法获取特定项目的总数量。如果我使用 sum(function) 它会返回所有数量的总和。我想要实现的是,如果同一商品有多个记录,则获取该特定商品数量的总和。这是类结构:

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

列表:

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

所以我想获得 ItemId = 1 的总数量,应该是 13。

那么获取特定 itemId 的总数量的最佳方法是什么?谢谢。

最佳答案

您需要按其 Id 对所有商品进行分组,即每个组的 Quantity 的计算总和。

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()

因此,您将获得匿名对象的集合,其中包含 myList 中的所有项目及其总数量。

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

您可以使用 CartItem 类来代替匿名类型,因为它在相同的上下文中具有相同的属性。所以 Select pert 看起来像这样:

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

关于vb.net - 从 VB.Net 列表中获取不同值的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45253812/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com