0

I know you can't modify a collection during a foreach, but I should be able to set variable values of the underlying iterator through it. For some reason the method below, every time it executes is giving be the "Collection was modified..." error:

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;
}

Am I just missing something easy here? The loop that is causing the exception is the second, this one:

foreach (var row in component.Schedule.ScheduleRows)
4

1 回答 1

0

我怀疑这不是 .NET 框架的东西,所以我假设该行连接到它的集合。修改行的内容,可能会改变它在集合中的位置,从而修改集合,这在某些 foreach 操作中是不允许的。

解决方案很简单:创建集合的副本(通过使用 LINQ)。

foreach (var row in component.Schedule.ScheduleRows.ToList())
    ...
于 2013-04-25T15:57:27.650 回答