3
votes

I have this code that removes a player if the player is not alive, but I figured the problem is to do with the foreach loop. I've seen solutions involving making new lists, but I cannot see how I can apply it to my code. Can anyone please shed some light?

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

3 Answers

3
votes

You can't modify the collection you are iterating over with foreach. What you need to do is add the items you want to remove to a new list, then once that list is built 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
votes

Query the collection for the players to delete:

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

Then delete the players:

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

You should remove the elements of a collection using a reverse for:

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