-3

I have defined a Dictionary as follows:

Dictionary<string, double> collection = new Dictionary<string, double>();

Now i want to update my Value:

foreach (KeyValuePair<string, double> pair int collection)
{
    double val = 3.0;
    collection[pair.Value] = val; // Get an error
}

My error is Cannot convert from double to string. Why is that ?

berry wer
  • 637
  • 2
  • 12
  • 25

2 Answers2

2

You can't iterate over a Dictionary and change the internal value as it will break the iterator.

you need to copy the collection, and modify the copied version...example below:

Dictionary<string, double> collection = new Dictionary<string, double>();
collection.Add("A", 1.0);
collection.Add("B", 2.0);

Dictionary<string, double> collection2 = new Dictionary<string, double>(collection);

foreach (KeyValuePair<string, double> pair in collection)
{
  double val = 3.0;              
  collection2.Remove(pair.Key);
  collection2.Add(pair.Key, val);
 }
Christian Phillips
  • 18,399
  • 8
  • 53
  • 82
0

Try this

   Dictionary<string, double> Copycollection= new Dictionary<string, double>  (collections);
            foreach (KeyValuePair<string, double> pair in Copycollection)
             {
                double val = 3.0;
                collection[pair.Key] = val; 
            }
Arash
  • 889
  • 7
  • 18
  • 1
    This won't work as you are not allowed to change collection during enumerating. See [related](http://stackoverflow.com/q/2260446/1997232) question. – Sinatr Oct 01 '15 at 11:25