在foreach错误期间修改的集合
本文关键字:修改 集合 foreach 错误 | 更新日期: 2023-09-27 18:10:58
我知道你不能在foreach
期间修改集合,但我应该能够通过它设置底层迭代器的变量值。由于某些原因,下面的方法每次执行时都会给出"Collection was modified…"错误:
private static IInstrument AdjustForSimpleInstrument(DateTime valueDate, IInstrument temp)
{
var instr = temp;
foreach (var component in instr.Components)
{
component.Schedule.ScheduleRows.RemoveAll(
sr =>
((sr.Payment != null) && (sr.Payment.PaymentDate != null) &&
(sr.Payment.PaymentDate.AdjustedDate.Date <= valueDate.Date)));
if (
!component.ScheduleInputs.ScheduleType.In(ComponentType.Floating, ComponentType.FloatingLeg,
ComponentType.Cap, ComponentType.Floor)) continue;
foreach (var row in component.Schedule.ScheduleRows)
{
var clearRate = false;
if (row.Payment.CompoundingPeriods != null)
{
if (row.Payment.CompoundingPeriods.Count > 0)
{
foreach (
var period in
row.Payment.CompoundingPeriods.Where(
period => ((FloatingRate)period.Rate).ResetDate.FixingDate > valueDate))
{
period.Rate.IndexRate = null;
clearRate = true;
}
}
}
else if (row.Payment.PaymentRate is FloatingRate)
{
if (((FloatingRate)row.Payment.PaymentRate).ResetDate.FixingDate > valueDate)
clearRate = true;
}
else if (row.Payment.PaymentRate is MultipleResetRate)
{
if (
((MultipleResetRate)row.Payment.PaymentRate).ChildRates.Any(
rate => rate.ResetDate.FixingDate > valueDate))
{
clearRate = true;
}
}
if (clearRate)
{
row.Payment.PaymentRate.IndexRate = null;
}
}
}
return temp;
}
我是不是错过了一些简单的东西?导致异常的循环是第二个,这一个:
foreach (var row in component.Schedule.ScheduleRows)
我怀疑这不是。net框架的东西,所以我假设行连接到它的集合。修改行内容可能会改变其在集合中的位置,从而修改集合,这在某些foreach操作中是不允许的。
解决方案很简单:创建一个集合的副本(通过使用LINQ)。foreach (var row in component.Schedule.ScheduleRows.ToList())
...