C# 中的 Delete() 和 Update() 函数,无需使用 LINQ



所以我写了一个基本的库存系统代码,我的代码在更新上有一个基本的错误,列表中的完整项目是更新的,而不是作为参数传递的首选id,删除函数显示的错误是"Collection was modified;枚举操作不能执行。"我还是初学者

//This is my update method
public void Update(int prodID)
{
if (prodID <= ProductList.Count)
{
foreach (Product p in ProductList)
{
if (ProductList.Exists(p => p.ProductId == prodID))
{
Console.WriteLine("Product Name:");
string Name = Console.ReadLine();
Console.WriteLine("Product No.:");
string Productno = Console.ReadLine();
Console.WriteLine("Price:");
decimal Price = int.Parse(Console.ReadLine());
p.ProductName = Name;
p.ProductNo = Productno;
p.ListPrice = Price;
}
}
}
else
{
Console.WriteLine("ENTER A VALID PRODUCT IDn");
}
}

//This is my Delete method
public void Delete(int prodID)
{ 
if (prodID <= ProductList.Count)
{
foreach (Product p in ProductList)
{                    
if (ProductList.Exists(p => p.ProductId == prodID))
{
ProductList.RemoveAt(prodID - 1);
Console.WriteLine("THE PRODUCT IS SUCCESSFULLY DELETED.n");
}    
}
}
else
{
Console.WriteLine("ENTER A VALID PRODUCT IDn");
}           
}

第二部分也是。

尝试在foreach (Product p in ProductList)后添加.ToList()

public void Delete(int prodID)
{ 
if (prodID <= ProductList.Count)
{
foreach (Product p in ProductList.ToList())
{                    
if (ProductList.Exists(p => p.ProductId == prodID))
{
ProductList.RemoveAt(prodID - 1);
Console.WriteLine("THE PRODUCT IS SUCCESSFULLY DELETED.n");
}    
}
}
else
{
Console.WriteLine("ENTER A VALID PRODUCT IDn");
}           
}

如果调用toList(),将会"生成"一个分隔列表。所以foreach使用了另一个列表,而不是原来的列表ProductList。这意味着您可以编辑和删除ProductList中的项目,而不会出现任何问题。

希望这对你有用。


代码优化你也可以尝试使用。select和。where来选择你的列表中的特定项目。我不知道你的代码,但通常你可以像这样在对象列表中选择特定的项。

public void Update(int prodID)
{
var product = ProductList.Where(p => p.ProductId == prodID).FirstOrDefault();
if (product != null) {
Console.WriteLine("Product Name:");
string Name = Console.ReadLine();
Console.WriteLine("Product No.:");
string Productno = Console.ReadLine();
Console.WriteLine("Price:");
decimal Price = int.Parse(Console.ReadLine());
p.ProductName = Name;
p.ProductNo = Productno;
p.ListPrice = Price;
}
else
{
Console.WriteLine("ENTER A VALID PRODUCT IDn");
}
}

我只能回答第二部分

foreach不能用于集合——它只能用于枚举数。虽然集合可以隐式转换为枚举数,但这种转换使它们受制于枚举数规则。

其中一条规则是:"如果底层集合被修改,Enumerator应该变为无效"。这正在这里发生。因此,如果您计划修改集合(通过添加,删除或替换),则不能使用foreach。

最新更新