在foreach错误期间修改的集合

时间:2013-04-25 15:29:21

标签: c# .net collections foreach iterator

我知道你不能在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)

1 个答案:

答案 0 :(得分:0)

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

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

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