-3

I have a dictionary of which I want to modify the key by removing the previous one and adding a new one and then Iterating over it again and again. Here is the declaration of dictionary

   Dictionary<string, List<Entity>> SuggestedDictionary = new Dictionary<string, List<Entity>>

And: The other dictionary is :

   Dictionary<string, List<Entity>> CopyDataDict = new Dictionary<string, List<Entity>>

After that I populate data in the dictionary using Dict.Add().

List<Entity> list = db.books.ToList();
foreach(var l in list)
{
   list.Add(l);
}
SuggestedDictionary.Add("Key", list);
CopyDataDict.Add("Key", list); 

Then I iterate over the data as follows:

foreach (var entry in CopyDataDict.Values.ToList())
{
    for (int i = 2; i < 15; i++) //just 14 items will be added
    {
        foreach (var container in SuggestedDictionary.Keys)
        {
            rec.Add(new Recommendations() { bookName = container, Rate = CalculatePearsonCorrelation(bkName, container) });
        }


        SuggestedDictionary.Remove(SuggestedDictionary.Keys.ToString());


        if (!SuggestedDictionary.ContainsKey(entry[i].bookName))
        {
            SuggestedDictionary.Add(entry[i].bookName, list);
        }
    }

When I run the code, it says The Collection has been modified enumeration operator may not execute. How Can I fix it or is there a better solution to do the same thing.

mjwills
  • 23,389
  • 6
  • 40
  • 63
Muhammad Shahid
  • 81
  • 2
  • 12
  • 2
    I think this code doesn't throw the exception. I don't see a closing bracket of foreach loop, please provide full code of that loop – opewix Jan 19 '19 at 13:06
  • Possible duplicate of [Different behaviour when collection modified between Dictionary and ConcurrentDictionary](https://stackoverflow.com/questions/28480150/different-behaviour-when-collection-modified-between-dictionary-and-concurrentdi) – mjwills Jan 19 '19 at 13:09
  • @mjwills please have a look on the edited code it is minimal complete working code – Muhammad Shahid Jan 19 '19 at 13:26
  • I just reformatted your code so it becomes clear that a `}` is missing somewhere. Can you please edit it? – Klaus Gütter Jan 19 '19 at 13:50

2 Answers2

2

I just ran your code, it has nothing to do with adding or removing the key. You get the error when you populate your list object

List<Entity> list = db.books.ToList();
foreach(var l in list)
{
   list.Add(l);
}

you are having already a list of books so what is the purpose of the foreach loop?

You get the error because you add new objects while enumerating over the list, this is not allowed because it will be infinitive

Aldert
  • 4,209
  • 1
  • 9
  • 23
0

Your problem starts with the following code:

List<Entity> list = new DomainModelDbContext().books.ToList();

foreach (var l in list)
{
    list.Add(l); // Runtime error
}

Generally speaking, you can't add or remove items in a collection or dictionary while iterating it over using the foreach loop. This issue will not happen if you use other type of loops such as for(...), while loop, etc.

Tanveer Yousuf
  • 386
  • 1
  • 3
  • 16
  • Yes I got it I was looping over again and again now my code runs fine. but as a matter of fact the query takes a long time to execute. is there a smarter way to do it. – Muhammad Shahid Jan 19 '19 at 14:42
  • Which line of your code is slow exactly? How many records it’s fetching from the DB? – Tanveer Yousuf Jan 19 '19 at 15:28
  • Not a big problem I have limited the results using Take(num). Infact I have some eleven thousand records and I am using core i5. That is why query was slow. – Muhammad Shahid Jan 19 '19 at 20:07