The collection has been changed; enumeration operation may fail

I have this code that removes the player if the player is not alive, but I figured the problem was with a loop foreach

. I've seen solutions related to creating new lists, but I don't see how I can apply it to my code. Can anyone shed some light on this?

private Dictionary<int, Player> numPlayers = new Dictionary<int, Player>();

private void CheckPlayers()
{
    foreach (Player player in numPlayers.Values)
    {
        if (!player.isAlive)
        {
            canvas.Children.Remove(player.hand);
            numPlayers.Remove(player.id); // breaks here
        }
    }
}

      

+3


source to share


3 answers


Request a collection to remove players:

var playersToDelete = numPlayers.Values.Where(p => !p.isAlive).ToList();

      



Then remove the players:

foreach(var player in playersToDelete) {
    canvas.Children.Remove(player.hand);
    numPlayers.Remove(player.id);
}

      

+3


source


You cannot change the collection you are doing with foreach

. You need to add the items you want to remove to the new list, after this list is created, remove them.



var dead = numPlayers.Values
    .Where(p => !p.isAlive)
    .ToList();

foreach(var player in dead)
{
    canvas.Children.Remove(player.hand);
    numPlayer.Remove(player.id);
}

      

+3


source


You have to remove the elements of the collection using the inverse for:

for(int i = numPlayers.Values.Count - 1; i <= 0; i--)
{
//Remove it.
}

      

0


source







All Articles