首页 > 解决方案 > 如何检查arraylist是否已经包含一个对象

问题描述

我试图让我的购物车识别一个项目是否已经添加到购物车中,然后将数量更新为一个,但它只是让声明为假。

这是我的页面加载处理程序,它从查询字符串中发送的详细信息创建一个新产品。

Private Sub ShoppingCartPage_Load(sender As Object, e As EventArgs) Handles Me.Load
    If Not (IsPostBack) Then
        If Not (Request.QueryString.ToString().Length.Equals(0)) Then
            Dim newProduct As Product = New Product(Request.QueryString("ProductCode"), Request.QueryString("ProductName"), Request.QueryString("Category"), Val(Request.QueryString("Price")), Request.QueryString("Description"))

            If Session("shoppingCartSession") Is Nothing Then
                shoppingCart = New ArrayList()
                shoppingCart.Add(newProduct)
                Session("shoppingCartSession") = shoppingCart
            ElseIf (shoppingCart.Contains(newProduct.itemID)) Then
                For Each item As Product In shoppingCart
                    If item.Equals(Request.QueryString("ProductCode")) Then
                        item.updateQuantity()
                    End If
                Next

            Else
                shoppingCart = CType(Session("shoppingCartSession"), ArrayList)
                shoppingCart.Add(newProduct)
                Session.Add("shoppingCartSession", shoppingCart)
            End If
        End If
        shoppingCart = CType(Session("shoppingCartSession"), ArrayList)
        createShoppingCartTable()
    End If

End Sub

标签: asp.netvb.netwebforms

解决方案


这里有很多问题。首先,如果您要添加ArrayList这样的内容:

shoppingCart.Add(newProduct)

然后你正在添加Product对象。在那种情况下,您为什么希望这很有用:

If (shoppingCart.Contains(newProduct.itemID)) Then

newProduct.itemID大概是一个Integer或类似的,所以当然集合不包含它。它不包含任何Integer值,因为它包含Product对象。您需要检查它是否包含Product带有 that 的对象,而itemID不是它是否itemID直接包含该对象。我会替换所有这些:

If Session("shoppingCartSession") Is Nothing Then
    shoppingCart = New ArrayList()
    shoppingCart.Add(newProduct)
    Session("shoppingCartSession") = shoppingCart
ElseIf (shoppingCart.Contains(newProduct.itemID)) Then
    For Each item As Product In shoppingCart
        If item.Equals(Request.QueryString("ProductCode")) Then
            item.updateQuantity()
        End If
    Next

Else
    shoppingCart = CType(Session("shoppingCartSession"), ArrayList)
    shoppingCart.Add(newProduct)
    Session.Add("shoppingCartSession", shoppingCart)
End If

有了这个:

shoppingCart = TryCast(Session("shoppingCartSession"), ArrayList)

If shoppingCart Is Nothing Then
    shoppingCart = New ArrayList
    Session("shoppingCartSession") = shoppingCart
End If

Dim existingProduct = shoppingCart.Cast(Of Product)().
                                   SingleOrDefault(Function(p) p.itemID = newProduct.itemID)

If existingProduct Is Nothing Then
    shoppingCart.Add(newProduct)
Else
    existingProduct.updateQualtity()
End If

也就是说,我也会遵循@VisualVincent 的建议并使用 aList(Of Product)而不是ArrayList. 如果你这样做,那么你可以Cast在我建议的代码中省略调用。


推荐阅读