c# - Collection modified during foreach error -


i know can't modify collection during foreach, should able set variable values of underlying iterator through it. reason method below, every time executes giving "collection 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 floatingrate)             {                 if (((floatingrate)row.payment.paymentrate).resetdate.fixingdate > valuedate)                     clearrate = true;             }             else if (row.payment.paymentrate 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 missing easy here? loop causing exception second, one:

foreach (var row in component.schedule.schedulerows) 

i suspect not .net-framework stuff, assume row connected collection. modifying contents of row, might shift place inside collection, modifying collection, not allowed during foreach-operations.

the solution simple: create copy of collection (by using linq).

foreach (var row in component.schedule.schedulerows.tolist())     ... 

Popular posts from this blog

How to calculate SNR of signals in MATLAB? -

c# - Attempting to upload to FTP: System.Net.WebException: System error -

ios - UISlider customization: how to properly add shadow to custom knob image -