Click here to Skip to main content
15,921,203 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hey guys, I'm getting a Collection was modified; enumeration operation may not execute. error. Everyting is working fine and saving i just get spat that error still.
C#
public static void addItem(SocketUser user, SocketGuild guild, Item item, int amount)
{
    checkUser(user, guild);
    if (getItemList(guild).ContainsKey(item.Id)) {
        List<localItem> inventory = getPlayerInventory(user, guild);
        List<string> playerList = getInventoryList(guild);
        if (inventoryContains(item, inventory)) {
            localItem local = new localItem();
            local = getLocalItem(inventory, item);
            inventory.Remove(getLocalItem(inventory, item));
            local.amount += amount;
            inventory.Add(local);
        }
        else
        {
            localItem local = new localItem();
            local.item = item;
            local.amount += amount;
            inventory.Add(local);
        }
        foreach (string line in playerList)
        {
            if (line.Contains(user.Id.ToString()))
            {
                string newline = embedInventoryString(user.Id.ToString(), inventory);
                playerList.Remove(line);
                playerList.Add(newline);
                File.WriteAllLines("server data\\inventoryData" + guild.Id.ToString() + ".json", playerList);
                Console.WriteLine("done 2");
            }
        }
    }
}


What I have tried:

I've tried moving the File.WriteAllLines around because i was thinking it was just being modified at the wrong time, i don't see anything wrong with the code?
Posted
Updated 5-Jul-18 19:26pm

You can't modify the collection playerList while iterating through it using foreach.  Instead, walk the list using an indexer.

/ravi
 
Share this answer
 
To add to what Ravi said, that's also a very inefficient way to do it.
Have a look here: List<T> - Is it really as efficient as you probably think?[^]

The way I would do your task is to construct a new playerList of the right size and either copy the old element over, or replace it with the new one.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900