使用条件获取链接列表中的下一个元素

时间:2017-03-14 13:10:19

标签: c# linked-list

我在游戏中使用链接列表进行转弯管理。我有玩家,我遍历他们,但是当一个玩家完成游戏时,他需要被跳过,这是我失败的地方。

我该怎么做?这就是我现在所拥有的:

public Player GetNextPlayer() {
        var current = linkedPlayerList.Find(currentPlayer);

        Player nextPlayer = current.Next == null ? linkedPlayerList.First.Value : current.Next.Value;

        SetCurrentPlayer(nextPlayer);
        return nextPlayer;
}

我尝试了以下但是它不起作用。

Player nextPlayer = current.Next == null
   ? linkedPlayerList.First(f => !f.RoundCompleted)
   : current.Next.List.Where(w=>!w.RoundCompleted).ElementAt(linkedPlayerList.ToList().IndexOf(currentPlayer));

2 个答案:

答案 0 :(得分:1)

我会用一个循环来检查你的病情。代码中的注释来解释。

LinkedList<Player> linkedPlayerList = ......;
Player currentPlayer = .......;

public Player GetNextPlayer()
{
    // Find the current node
    var curNode = linkedPlayerList.Find(currentPlayer);

    // Point to the next
    LinkedListNode<Player> nextNode = curNode.Next;

    // Check if at the end of the list
    nextNode = nextNode == null ? linkedPlayerList.First : nextNode;    

    // Loop stops when we find the condition true or we reach the starting point
    while (curNode != nextNode)
    {
        // Exit if found....
        if (!nextNode.Value.RoundCompleted)
            break;
        // Manage the next node to check for....
        nextNode = nextNode?.Next == null ? linkedPlayerList.First : nextNode.Next;    
    }
    SetCurrentPlayer(nextNode.Value);
    return nextNode.Value;
}

答案 1 :(得分:0)

您可以执行以下操作(下一步添加额外的空检查):

Player nextPlayer = current.Next.List.FirstOrDefault (x => !.RoundCompleted);