Resolved Getting dictionary default value

johnss

New member
Joined
May 11, 2020
Messages
4
Programming Experience
Beginner
I have a foreach loop like the following:

C#:
        private Dictionary<string,double> SumDictDaysExpDetail(Dictionary<int,Dictionary<string,string>> ddd)
        {
            Dictionary<string, double> dsum = appDataContext.MyFields.ToDictionary(l => l.drName, l => 0.0);

            foreach (string k in dsum.Keys)
            {
                List<string> ls = ddd.Select(l => l.Value.ContainsKey(k) ? l.Value[k] : "0,00").ToList();

                dsum[k] = ls.Sum(l => Convert.ToDouble(l));
            }

            return dsum;
        }

that I run with my dictionary ddd. I intend to calculate the sum for each header in a table, where the first int is the day of the month...
Now, when I run this loop I obtain a error saying that 'Collection was modified; enumeration operation may not execute.'.

But I don't alter the dictionary, at least consciously. When I use l.Value[k] ?? "0,00" gives also an error.

It seems that the use of .ContainsKey creates a key in the dictionary...

How may I do this?
 
 
On line 5 you are iterating over the keys of the the dsum collection. Your line #9 is updating the dsum collection.

What you can do is change this:
C#:
foreach (string k in dsum.Keys)
to this:
C#:
foreach (string k in dsum.Keys.ToList())
to force getting a copy of all the keys before you start partying on the collection. Make sure this is truly you want to do, though.
 
You have a link - I provided one on p/#3 which shows how to deal with it. As the problem you are reporting is the same one i addressed on that other topic.

What I linked you isn't much different to what Skydiver is tell you to do.

Do you understand why this is causing you problems?
 
Yes, I understand. I solved the problem with a copy of the keys as you both said.
However, I believe that the problem arises from line #8 because .ContainsKey somehow messes with the dictionary.
Thank you.
 
The problem happens when the collection you iterate has one of its values changed while the collection is being navigated at the same time; you can't do that. And its not because you check a condition of the iteration itself, since checking a condition of any iteration won't cause a problem. You can not change a collection value while said collection is being cycled through.

And you're welcome.
 

Latest posts

Back
Top Bottom