asp.net - 如何检查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
解决方案
这里有很多问题。首先,如果您要添加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
在我建议的代码中省略调用。
推荐阅读
- flutter - 如何从颤振访问谷歌云数据存储?
- javascript - 我可以在这样的地图内映射吗?
- reactjs - 如何根据 React.js 中的按钮单击来聚焦元素
- c++ - 什么时候应该使用`std::atomic`?
- sql - PostgreSQL 检查数组中的至少一项是否在字符串中
- node.js - 如何保护 Web API 免受未经授权的使用
- javascript - 如何使用基于当前 url 的 javascript 在 jsp 文件中设置 div 项的活动菜单状态?
- pandas - 如何使用源 DataFrame 中满足条件的值更新目标 DataFrame?
- javascript - Vue 导航守卫在 localStorage 硬刷新之前运行
- react-native - 如何在 iOS 中使用 resizeMode 反应原生?