c# - Error when calling a method in foreach with object -


i have list objects of strings , doubles, , try call different methods based on itemtype , value. in debugger can see first iteration works fine, error shows when entering second time after method called.
if comment out methods , put in simple methods works, understand how call methods.

what do wrong, , can make work?
if there easier ways i'm trying, please let me know.

public double evaluateexpressionusingvariablevalues(list<object> anexpression, dictionary<string, double> variables)   {       foreach (object element in anexpression)       {            if(element.gettype()!=typeof(string))           {               setoperand((double)element);           }           else if (element.gettype() == typeof(string))           {               if (!element.tostring().startswith("%"))               performoperation((string)element);           else               setoperand(variables[element.tostring()]);            }        }            return this.operand;   }   

if methods (setoperand, performoperation) modify collection @ all, exception. can't modify collection while iterating on it. 1 method create result collection , add items change them, rather trying modify collection in-place.

private void foo() {   foreach(var item in items) {     if (item.isbad) {       deleteitem(item); // throw exception tries modify items     }   } }  private void deleteitem(item item) {   items.remove(item); } 

instead, try:

private void foo() {   list<item> result = new list<item>();   foreach(var item in items) {     if (!item.isbad) {       result.add(item); // adding collection other                         // 1 iterating through     }   }   items = result; // no longer iterating, can modify                   // collection } 

Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -