gpt4 book ai didi

c# - 无法从列表中删除项目

转载 作者:太空宇宙 更新时间:2023-11-03 22:50:27 25 4
gpt4 key购买 nike

我尝试在 DeleteProduct 方法中从产品中删除项目,并且 Remove 方法返回 true 但所有项目仍在列表中,我不明白为什么。

据我所知,产品列表是在应用程序第一次启动时创建的,在静态构造函数中它会填充项目。然后在 DeleteProduct 方法中,其中一项删除并执行 Products 方法。

请大神解释一下!

public class ProductController
: Controller
{
private static IEnumerable<ProductViewModel> products = null;

static ProductController()
{
products = new List<ProductViewModel>
{
new ProductViewModel{Id = 0, Description = "Milk", Price = 21.0, IsAvailable = true, LastUpdate = DateTime.Now},
new ProductViewModel{Id = 1, Description = "Bread", Price = 10.10, IsAvailable = false, LastUpdate = DateTime.Now},
new ProductViewModel{Id = 2, Description = "Soure creame", Price = 34.5, IsAvailable = true, LastUpdate = DateTime.Now},
new ProductViewModel{Id = 3, Description = "Chocolate", Price = 31.0, IsAvailable = true, LastUpdate = DateTime.Now},
new ProductViewModel{Id = 4, Description = "Apples", Price = 1.0, IsAvailable = true, LastUpdate = DateTime.Now},
};
}
public ActionResult Products()
{
return View(products);
}

public ActionResult DeleteProduct(int id)
{
var product = products.FirstOrDefault(p => p.Id == id);

if (product != null)
products.ToList().Remove(product);

return RedirectToAction("Products");
}
}

最佳答案

问题出在那行:

products.ToList().Remove(product);

通过调用 ToList(),您可以生成一个新列表并从新创建的列表中删除产品。为了使代码工作,将产品字段更改为类型 List:

private static List<ProductViewModel> products = null;

这样,您就可以使用列表的方法,而不必强制转换或使用 ToList()。您可以直接在产品字段上调用 ​​Remove:

products.Remove(product);

关于c# - 无法从列表中删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47607358/

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