将Func传递给List.Find

时间:2012-09-22 15:40:08

标签: c# func

我有以下代码:

    [TestMethod]
    public void A_Player_Can_Be_Deleted_From_The_List()
    {                     
        Player player = playerList.Find(ByName("Davy",whatGoesHere?);
        playerList.Remove(player);

        playerList.Count.Should().Be(2);
    }

Func'ByName'定义为:

Func<string, Player, bool> ByName = (name, player) => player.Name == name;

我不知道如何传递第二个(播放器)参数。有可能吗?

2 个答案:

答案 0 :(得分:1)

player被提供给您传递给List.Find<T>的谓词,因此您只需将其传递给ByName

Player player = playerList.Find(p => ByName("Davy", p));
playerList.Remove(player);

您可以使用List<T>.RemoveAll,而不是FindRemove

playerList.RemoveAll(p => ByName("Davy", p));

答案 1 :(得分:1)

如果要在ByName方法中使用Find委托,则必须为列表中的每个元素执行该委托。例如:

string player = playerList.Find((playerElement) => ByName("Davy", playerElement));