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
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 to share