Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through Queue in c# while Dequeue for each iteration

Tags:

c#

.net

queue

I am building a console card game in c#.

I have one dealer and 4 players and I want the dealer to play with each player alone. So, I have put the players in a Queue so that they may be served in order.

My problem is when iterating through all the players in the Queue. When I run my logic (seen below), the for loop will only execute 2 times because the playerQueue is decreasing while the i variable is increasing.

Please help me find a way to rectify this.
I attempted a While loop, but it did not work because we manipulate playerQueue.Count().

Queue<Player> playerQueue = new Queue<Player>();

int number_of_players = 4;


/// <summary>
///  Adds new player to Queue
/// </summary> 
for (int i = 0; i < number_of_players; i++)
{
    Player player = new Player();
    playerQueue.Enqueue(player);
}

/// <summary>
///  Get the first player in the playerQueue
/// </summary>  

// HERE IS THE PROBLEM
for (int i = 0; i < playerQueue.Count(); i++)
{ 
     System.Console.WriteLine(playerQueue.Count());
     System.Console.WriteLine(i);

     // Get the first player in the playerQueue 
     Player PlayerInGame = playerQueue.Dequeue();

    // Play the game with the current player in the queue
}
like image 630
charles Avatar asked Dec 07 '25 10:12

charles


1 Answers

Below, I updated the codebase so that the for loop is no longer dependent on the count within the queue. Instead, it has a condition checking if there are any waiting in line. Please refer to the code below.

Queue<Player> playerQueue = new Queue<Player>();

int number_of_players = 4;


/// <summary>
///  Adds new player to Queue
/// </summary> 
for (int i = 0; i < number_of_players; i++)
{
    Player player = new Player();
    playerQueue.Enqueue(player);
}

/// <summary>
///  Get the first player in the playerQueue
/// </summary>  

// HERE IS THE SOLUTION
while(playerQueue.Any())
{ 
     System.Console.WriteLine(playerQueue.Count());
     System.Console.WriteLine(i);

     // Get the first player in the playerQueue 
     Player PlayerInGame = playerQueue.Dequeue();

    // Play the game with the current player in the queue
}
like image 93
Impurity Avatar answered Dec 10 '25 00:12

Impurity