c# - System.InvalidOperationException: Collection was modified error -


i have system.invalidoperationexception: collection modified error, can see output of console here .

here code, removed many lines, structure easier read.

static public void searchcode2(dictionary<string, string> mlist)     {          using (sqlconnection connection3 = new sqlconnection(configurationmanager.connectionstrings["db"].connectionstring))         {               connection3.open();             sqlcommand command2 = new sqlcommand(null, connection3);              var keyswithmatchingvalues = mlist.where(p => equals(p.value, "0")).select(p => p.key);              // ce devrait macher, meme s'il y plusieurs requetes             // tthe fallowing line error point out.             foreach (var key in keyswithmatchingvalues)             {                  console.writeline(" missing list");                 string[] mottocut = key.tostring().split(' ');                 dictionary<string, int> movieslistmissing = new dictionary<string, int>();                 dictionary<string, string> movieslistmissingcode = new dictionary<string, string>();                 dictionary<string, datetime> movieslistmissingdate = new dictionary<string, datetime>();                   //// on va chercher si un des elements du dico n'a pas été récupéré.                 command2.commandtext = "";                 int counter = 0;                  foreach (string word_cutted in mottocut)                 {                     // on considere que les mots qui ont plus d'une lettre                     if (word_cutted.length > 1)                     {                          command2.commandtext += "select code, titre, date data titre '%" + word_cutted + "%';";                         counter++;                         console.writeline("word_cutted : {0} ", word_cutted);                     }                 }                  command2.prepare();  // calling prepare after having set commandtext , parameters.                  sqldatareader reader2 = command2.executereader();                   try                 {                        (int = 0; < counter; i++)                     {                         //codes                     }                     bool movieslistmissingisempty = (movieslistmissing.count == 0);                     if (!movieslistmissingisempty)                     {                           //codes                     }                      // liste le dictionnaire                     foreach (string key2 in mlist.keys)                     {                         console.writeline("last version : {0}, {1} ", key2, mlist[key2]);                     }                   }                 catch (exception e)                 {                     //console.writeline("{0} exception caught.", e);                     console.writeline("last version : {0}", e);                 }                                 {                     // call close when done reading.                     reader2.close();                  }              }              connection3.close();             // won't print             console.writeline(" avant var key in keyswithmatchingvalues ");            }       } 

for reason put after

 connection3.close(); 

won't work, , can't figure out reason. in similar topics, said use lock function, don't where. ( tried places did not work).

here complete code if may help:

   static public void searchcode2(dictionary<string, string> mlist)     {          using (sqlconnection connection3 = new sqlconnection(configurationmanager.connectionstrings["distridbentities2"].connectionstring))         {               connection3.open();             sqlcommand command2 = new sqlcommand(null, connection3);              datetime today = datetime.now;             bool pbbool = false;             string motfinal = "";             var keyswithmatchingvalues = mlist.where(p => equals(p.value, "0")).select(p => p.key);             //where(p => p.value == "a").select(p => p.key);              // ce devrait macher, meme s'il y plusieurs requetes              foreach (var key in keyswithmatchingvalues)             {                  pbbool = true;                 console.writeline(" missing list");                 //literaltest.text += "<br/>" + motfinal + ", original: " + key + "<br/>";                 string[] mottocut = key.tostring().split(' ');                 dictionary<string, int> movieslistmissing = new dictionary<string, int>();                 dictionary<string, string> movieslistmissingcode = new dictionary<string, string>();                 dictionary<string, datetime> movieslistmissingdate = new dictionary<string, datetime>();                   //// on va chercher si un des elements du dico n'a pas été récupéré.                 command2.commandtext = "";                 int counter = 0;                  foreach (string word_cutted in mottocut)                 {                     // on considere que les mots qui ont plus d'une lettre                     if (word_cutted.length > 1)                     {                          command2.commandtext += "select code, titre, date data titre '%" + word_cutted + "%';";                         counter++;                         console.writeline("word_cutted : {0} ", word_cutted);                     }                 }                  command2.prepare();  // calling prepare after having set commandtext , parameters.                  //literaltest.text += "<br/> on rentre dans le try apres word_cutted : ";                  sqldatareader reader2 = command2.executereader();                   try                 {                       int resultcounter = 1;                     bool resultunique = false;                     string bontitre = "";                     (int = 0; < counter; i++)                     {                         if (i == 0)                         {                             while (reader2.read())                             {                                 //literaltest.text += "<br/> si = 0 ";                                 if (reader2[1].tostring().length > 0)                                 {                                     if (!movieslistmissing.containskey(reader2[1].tostring()))                                     {                                         //literaltest.text += "<br/> = 0   mot  : " + reader2[0].tostring() + "," + reader2[1].tostring();                                         movieslistmissing.add(reader2[1].tostring(), 0);                                         movieslistmissingcode.add(reader2[1].tostring(), reader2[0].tostring());                                         bontitre = reader2[1].tostring();                                         resultcounter++;                                         if (reader2[2].tostring().length > 0)                                         {                                             datetime dt = convert.todatetime(reader2[2].tostring());                                             //literaltest.text += "<br/> date conversion orginal:" + reader2[2].tostring() + " new : " + dt.tostring("dd/mm/yyyy");                                             movieslistmissingdate.add(reader2[1].tostring(), dt);                                         }                                     }                                 }                             }                         }                          else if (!resultunique)                         {                             // on réinitialise le compteur                             resultcounter = 1;                             reader2.nextresult();                             while (reader2.read())                             {                                 if (reader2[1].tostring().length > 0)                                 {                                     //literaltest.text += "<br/> :  " + + " mot : " + reader2[0].tostring() + "," + reader2[1].tostring();                                     if (!movieslistmissing.containskey(reader2[1].tostring()))                                     {                                         movieslistmissing.add(reader2[1].tostring(), 0);                                         movieslistmissingcode.add(reader2[1].tostring(), reader2[0].tostring());                                         movieslistmissingdate.add(reader2[1].tostring(), convert.todatetime(reader2[2].tostring()));                                         bontitre = reader2[1].tostring();                                     }                                     else                                     {                                         //on incremente le nombre de point.                                         movieslistmissing[reader2[1].tostring()] += 1;                                         bontitre = reader2[1].tostring();                                     }                                     resultcounter++;                                 }                             }                         }                         if (resultcounter == 2)                         {                             // si on eu qu'un retour lors d'une requete pour un mot alors c'est la bonne                             resultunique = true;                             console.writeline("resultunique true");                             //break;                         }                     }                     bool movieslistmissingisempty = (movieslistmissing.count == 0);                     if (!movieslistmissingisempty)                     {                         if (resultunique == false)                         {                             // liste le dictionnaire                             int keymax = 0;                             string truekey = movieslistmissing.keys.first();                             string falsekey = "";                             bool unique = true;                             // on regarde quel titre le plus de point.                             foreach (string cle in movieslistmissing.keys)                             {                                 if (movieslistmissing[cle] > keymax)                                 {                                     keymax = movieslistmissing[cle];                                     truekey = cle;                                     unique = true;                                     falsekey = "";                                 }                                 else if (movieslistmissing[cle] == keymax)                                 {                                     unique = false;                                     falsekey += cle + ", ";                                 }                             }                             console.writeline("le bon titre est : {0} ", truekey);                             console.writeline("le bon titre est unique ? : {0} falsekey: {1}", unique.tostring(), falsekey);                             // si le nombre max est détenue par un seul titre                             if (unique)                             {                                 bontitre = truekey;                                 // on rajoute le code                                 mlist[key.tostring()] = movieslistmissingcode[truekey];                             }                             else                             // on regarde la date                             {                                  string[] cuttedbydate = falsekey.tostring().split(' ');                                 datetime bestdate = movieslistmissingdate[cuttedbydate[0]];                                 bontitre = cuttedbydate[0];                                 foreach (string worddate in cuttedbydate)                                 {                                     if ((math.abs(today.subtract(movieslistmissingdate[cuttedbydate[0]]).days)) < math.abs(today.subtract(bestdate).days))                                     {                                         bontitre = worddate;                                     }                                 }                             }                         }                         else                         {                             console.writeline("le bon titre trouvé de maniere unique : {0} ", bontitre);                             mlist[key.tostring()] = movieslistmissingcode[bontitre];                         }                     }                      // liste le dictionnaire                     foreach (string key2 in mlist.keys)                     {                         console.writeline("last version : {0}, {1} ", key2, mlist[key2]);                     }                    }                 catch (exception e)                 {                     //console.writeline("{0} exception caught.", e);                     console.writeline("last version : {0}", e);                 }                                 {                     // call close when done reading.                     reader2.close();                  }              }              connection3.close();             console.writeline(" avant var key in keyswithmatchingvalues ");                       }       } 

okay, problem - you're modifying mlist while you're iterating through lazily evaluated query based on it:

mlist[key.tostring()] = movieslistmissingcode[bontitre]; 

and

mlist[key.tostring()] = movieslistmissingcode[truekey]; 

you're not allowed that.

the simplest way fix take copy of key/value pairs part of query. this:

var keyswithmatchingvalues = mlist.where(p => equals(p.value, "0")).select(p => p.key); 

can become:

var keyswithmatchingvalues = mlist.tolist()                                   .where(p => equals(p.value, "0"))                                   .select(p => p.key); 

although i'd rewrite as:

var keyswithmatchingvalues = mlist.tolist()                                   .where(p => p.value == "0")                                   .select(p => p.key); 

at point, you're fine modify mlist iterate on keyswithmatchingvalues, because they're separated.

(i'd break mammoth method smaller ones.)


Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

css - Firefox for ubuntu renders wrong colors -