收款已修改I发票分组
本文关键字:修改 | 更新日期: 2023-09-27 18:27:28
我有一个List<IGrouping<string, InvoiceCount>>
来检查发票中的头寸。它工作得很好,但当一个仓位已经在另一张发票中时,该仓位应该被删除,但它将出现异常
"集合已修改;枚举操作可能无法执行。"
我不知道该怎么解决
private static void ValidateInvoices(List<IGrouping<string, InvoiceCount>> invo)
{
var validationErrors = new StringBuilder();
foreach (IGrouping<string, InvoiceCount> invoice in invo)
{
for (var line = 1; line < invoice.Count(); line++)
{
if (!invoice.ElementAt(line).IsInSameInvoice(invoice.First()))
{
validationErrors.Append("Validation error in Invoice" + invoice.Key + " in line " + (line + 1) + Environment.NewLine);
if (invo.Contains(invoice))
try
{
invo.Remove(invoice);
}
catch (Exception ex)
{
throw ex;
}
}
}
}
if (validationErrors.Length > 0)
throw new Exception(validationErrors.ToString());
}
删除元素后需要刷新集合。试着像下面这样更改你的代码,看看它是否有效:
代码:
var newList = invo;
foreach (IGrouping<string, InvoiceCount> invoice in invo)
{
for (var line = 1; line < invoice.Count(); line++)
{
if (YOUR CONDITION HERE)
{
newList.Remove(invoice );
invo= newList;
}
}
}
注意:如何在迭代期间修改集合