带参数的C#FindIndex

带参数的C#FindIndex,c#,list,find,exists,C#,List,Find,Exists,我目前正在修补我最近发布的游戏 我有一个类的列表,叫做appliedefects。从该类生成的列表名为appliedefects。 我想访问这个列表并在索引中找到一个特定的值,然后根据列表中是否存在该值来设置bool true或false。它适用于通电系统,其中列表为当前激活的所有通电。例如,用于射击子弹的代码将搜索列表中是否有ID为1的项目,因为这是双子弹通电的ID 我已经走了这么远,但只有一个小问题: int ndx = PlayerStatus.appliedEffects.FindInd

我目前正在修补我最近发布的游戏

我有一个类的列表,叫做appliedefects。从该类生成的列表名为appliedefects。 我想访问这个列表并在索引中找到一个特定的值,然后根据列表中是否存在该值来设置bool true或false。它适用于通电系统,其中列表为当前激活的所有通电。例如,用于射击子弹的代码将搜索列表中是否有ID为1的项目,因为这是双子弹通电的ID

我已经走了这么远,但只有一个小问题:

int ndx = PlayerStatus.appliedEffects.FindIndex(PlayerStatus.FindAE(XX,1);
XX在哪里,我不知道该放什么。我编辑了这个:

int ndx = Books.FindIndex(FindComputer);
private static bool FindComputer(Book bk)
{
    if (bk.Genre == "Computer")
    {
        return true;
    }
    else
    {
        return false;
    }
}
因为在代码示例中,我无法发送要搜索的参数。编辑的代码如下所示:

public static bool FindAE(AppliedEffects ae, int id)
{
    if (ae.id == id)
    {
        return true;
    }
    else
    {
        return false;
    }
}
我创建了一个int,它将获得ID为1的项所在列表的索引,如果该值为1,因为ID为1,它将bool设置为true,如果不是,则设置为false。 我想为ID发送一个参数,而示例中没有,这样我就可以在其他ID检查中重用该函数。但是当我输入参数时,我不知道应该把什么作为appliedefect(这就是为什么我把XX)

我也试过:

if (PlayerStatus.appliedEffects.Exists(x => x.id == 1))
{
     PlayerStatus.doubleBullets = true;
}
这不起作用,不知道为什么。我不完全理解.Exists和.FindIndex的概念,所以可能这就是我不知道如何使用它的原因。 基本上,我只想能够检查列表中是否有具有特定ID的项目,这样游戏就会知道我有特定的通电,并且可以将bool设置为true,然后设置为false。 注意:ID不是索引,ID是appliedefects类中的一个int,它知道它是哪个加电。 我有点累,所以如果有任何想法/顾虑,请写在帖子里,我会订阅帖子

int ndx = PlayerStatus.appliedEffects.FindIndex(ae => PlayerStatus.FindAE(ae, 1));
FindIndex的参数是带有一个参数的方法/lambda。在这种情况下,将创建一个lambda,它接受单个参数
ae
,并返回
FindAE(ae,1)

FindAE
方法不是必需的。这样做可能更容易:

int ndx = PlayerStatus.appliedEffects.FindIndex(ae => ae.index == 1);
FindIndex的参数是带有一个参数的方法/lambda。在这种情况下,将创建一个lambda,它接受单个参数
ae
,并返回
FindAE(ae,1)

FindAE
方法不是必需的。这样做可能更容易:

int ndx = PlayerStatus.appliedEffects.FindIndex(ae => ae.index == 1);

请注意,如果未找到请求的元素,
FindIndex
将返回
-1
。因此,您必须这样做:

if(PlayerStatus.appliedEffects.FindIndex(ae => PlayerStatus.FindAE(ae, 1)) != -1)
{
    PlayerStatus.doubleBullets = true;
}
如您所述,在您的情况下使用
Exists
可能更有意义。试试这个:

if(PlayerStatus.appliedEffects.Exists(ae => PlayerStatus.FindAE(ae, 1)))
{
    PlayerStatus.doubleBullets = true;
} 

请注意,如果未找到请求的元素,
FindIndex
将返回
-1
。因此,您必须这样做:

if(PlayerStatus.appliedEffects.FindIndex(ae => PlayerStatus.FindAE(ae, 1)) != -1)
{
    PlayerStatus.doubleBullets = true;
}
如您所述,在您的情况下使用
Exists
可能更有意义。试试这个:

if(PlayerStatus.appliedEffects.Exists(ae => PlayerStatus.FindAE(ae, 1)))
{
    PlayerStatus.doubleBullets = true;
} 

另一方面,任何时候只要你有
if(condition){return true;}else{return false;}
你就可以用
返回条件来替换它。因此,您的
FindAE
方法主体可以是
return ae.id==idIf(condition){return true;}或者{return false;}
你可以用
return condition替换它。因此,您的
FindAE
方法主体可以是
return ae.id==id