C# 从存储在 ASP 会话中的列表中删除对象
C# Remove object from list stored in an ASP session
我正在制作一个小型电子书店作为一个项目。我将购物车作为对象列表存储在 ASP 会话中。现在,在结帐页面中,我在列表框中显示该对象列表,并允许用户在需要时删除项目。这是我的代码
protected void btnCart_Click(object sender, EventArgs e)
{
List<Title> cartItems = (List<Title>)Session["eStoreCart"];
int itemToRemove = Int32.Parse(lbCartItems.SelectedItem.Value);
Title ttl = ebs.Titles.SingleOrDefault(t => t.TitleId == itemToRemove);
cartItems.Remove(ttl);
Session["eStoreCart"] = cartItems;
FillListBox();
}
显然,调用 Remove() 方法前后 cartItems
中的项目数相同。我哪里错了?
在使用 cartItems.Add(ttl)
添加到卡片中使用了类似的方法,它工作得很好。
而不是
Title ttl = ebs.Titles.SingleOrDefault(t => t.TitleId == itemToRemove);
尝试
Title ttl = cartItems.SingleOrDefault(t => t.TitleId == itemToRemove);
即不要在 'ebs' 中搜索标题(不确定它包含什么,因为 OP 代码中不清楚),直接在 Session Object 中搜索项目然后将其删除。
.Remove()
方法is going to check for equality when trying to remove the item. Does Title
implement IEquatable<Title>
?如果不是,那么相等性检查将是默认的,对于对象来说是引用相等性。而且这里不太可能满足引用相等性。
实施 IEquatable<Title>
可能是这里的理想方法。只需将该接口添加到 Title
实现并实现它的一个方法:
public bool Equals(Title other)
{
if (other == null)
return false;
if (this.SomeValue == other.SomeValue)
return true;
else
return false;
}
这会将相等逻辑放在它所属的模型上。如果做不到这一点,您的代码在检查相等性时必须更加程序化。也就是说,您首先必须在 cartItems
中找到您要查找的元素,然后删除 that 对象,而不是尝试删除本身存在的对象在 ebs.Titles
。类似于:
cartItems.Remove(cartItems.Single(c => c.SomeValue == ttl.SomeValue));
这样代码将引用相同的内存中对象,而不仅仅是直观地表示相同事物的对象。
我正在制作一个小型电子书店作为一个项目。我将购物车作为对象列表存储在 ASP 会话中。现在,在结帐页面中,我在列表框中显示该对象列表,并允许用户在需要时删除项目。这是我的代码
protected void btnCart_Click(object sender, EventArgs e)
{
List<Title> cartItems = (List<Title>)Session["eStoreCart"];
int itemToRemove = Int32.Parse(lbCartItems.SelectedItem.Value);
Title ttl = ebs.Titles.SingleOrDefault(t => t.TitleId == itemToRemove);
cartItems.Remove(ttl);
Session["eStoreCart"] = cartItems;
FillListBox();
}
显然,调用 Remove() 方法前后 cartItems
中的项目数相同。我哪里错了?
在使用 cartItems.Add(ttl)
添加到卡片中使用了类似的方法,它工作得很好。
而不是
Title ttl = ebs.Titles.SingleOrDefault(t => t.TitleId == itemToRemove);
尝试
Title ttl = cartItems.SingleOrDefault(t => t.TitleId == itemToRemove);
即不要在 'ebs' 中搜索标题(不确定它包含什么,因为 OP 代码中不清楚),直接在 Session Object 中搜索项目然后将其删除。
.Remove()
方法is going to check for equality when trying to remove the item. Does Title
implement IEquatable<Title>
?如果不是,那么相等性检查将是默认的,对于对象来说是引用相等性。而且这里不太可能满足引用相等性。
实施 IEquatable<Title>
可能是这里的理想方法。只需将该接口添加到 Title
实现并实现它的一个方法:
public bool Equals(Title other)
{
if (other == null)
return false;
if (this.SomeValue == other.SomeValue)
return true;
else
return false;
}
这会将相等逻辑放在它所属的模型上。如果做不到这一点,您的代码在检查相等性时必须更加程序化。也就是说,您首先必须在 cartItems
中找到您要查找的元素,然后删除 that 对象,而不是尝试删除本身存在的对象在 ebs.Titles
。类似于:
cartItems.Remove(cartItems.Single(c => c.SomeValue == ttl.SomeValue));
这样代码将引用相同的内存中对象,而不仅仅是直观地表示相同事物的对象。