【发布时间】:2013-04-25 15:29:21
【问题描述】:
我知道您不能在foreach 期间修改集合,但我应该能够通过它设置底层迭代器的变量值。由于某种原因,下面的方法每次执行时都会出现“集合已修改...”错误:
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)
【问题讨论】:
-
有多个循环,你应该指定哪个导致异常...
-
对不起!添加。谢谢。
-
您还应该考虑将此方法重构为 2 或 3 个方法。你在嵌套循环中做了很多事情,而且条件嵌套越来越深。
-
是的,实际上现在正在重构,但在测试中发现了这个错误并试图找出原因..
-
也是嵌套的 ifs。考虑更改为 if(condition1 && condition2) 以进一步压缩该方法。
标签: c# .net collections foreach iterator