在每次迭代中出队的同时在c#中循环访问Queue

时间:2018-08-22 15:24:28

标签: c# .net queue

我正在用C#构建游戏机纸牌游戏。

我有1个发牌人和4个玩家,我希望该发牌人单独与每个玩家一起玩。因此,我将玩家放在Queue中,以便可以按顺序为他们服务。

我的问题是遍历Queue中的所有玩家时。当我运行逻辑时(如下所示),for循环将只执行2次,因为playerQueue变小而i变小了,而While变大了。

请帮助我找到纠正此问题的方法。
我尝试了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 } ,所以它不起作用。

{{1}}

1 个答案:

答案 0 :(得分:1)

下面,我更新了代码库,以便for循环不再依赖于队列中的计数。相反,它具有条件检查是否有任何排队等待。请参考下面的代码。

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
}