0

I read those articles:

First, second and third that is only for the case for deleting items, but I am not deleting them.

My Code:

 Dictionary<String, Object> tempList =(Dictionary<String,Object>)_ersetzeDasMitDas;

                //pfadFuerDieBildDatei
                foreach (KeyValuePair<string, Object> tempData in tempList)
                {
                    if (tempData.Key.Equals("fahrzeugGruppe"))
                    {
                        if (tempData.Value!=null)
                        {
                            if (tempData.Value.Equals("LKW"))
                            {
                                tempList["pfadFuerDieBildDatei"]=  Path.Combine(VirtualMachineKonstanten.statischeDateien, "lkw.png");
                            }
                            else if (tempData.Value.Equals("Transporter"))
                            {
                                tempList["pfadFuerDieBildDatei"]= Path.Combine(VirtualMachineKonstanten.statischeDateien, "transporter.png");
                            }
                            else
                            {
                                tempList["pfadFuerDieBildDatei"]= Path.Combine(VirtualMachineKonstanten.statischeDateien, "pkw.png");
                            }

                        }
                        else
                        {
                            //todo: logge Error "fahrzeugGruppe", der Wert ist null ?!
                            //erstmal für Testing
                            tempList["pfadFuerDieBildDatei"]= Path.Combine(VirtualMachineKonstanten.statischeDateien, "pkw.png");
                        }
                    }
            }

I get:

Collection was modified; enumeration operation may not execute,

after writing tempList["pfadFuerDieBildDatei"] and going again to the loop.

How to solve this ?

Community
  • 1
  • 1
kkkk00999
  • 179
  • 2
  • 13

1 Answers1

0

use the following code to get the updatable elements in the collection, then iterate through the new collection and do the updates:

var updatableCollection= tempList.Where(x => 
                          x.Key.Equals("fahrzeugGruppe") && x.Value != null)
                          .ToDictionary(x=> x.Key, x=> x.Value);
foreach (var item in updatableCollection)
{
   // check if (item.Value.Equals("LKW"))
   // update the required field
   // rest of condition and updates 
}
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
  • I get the same error, when using `var updatableCollection = tempList.Where(x => x.Key.Equals("fahrzeugGruppe")) .ToDictionary(x => x.Key, x => x.Value); foreach (var item in updatableCollection) { updatableCollection["pfadFuerDieBildDatei"] = Path.Combine(VirtualMachineKonstanten.statischeDateien, "pkw.png"); }` – kkkk00999 Apr 26 '16 at 13:43