检查给定的字符串是否存在于数组中

Sar*_*hrb 1 c# arrays

尝试检查Grapes中是否存在varieties,但下面的代码不满足 if 条件,即使数组中存在葡萄。

public enum Type
{   
    Apple,
    Orange,
    Grapes  
}


private Type[] varieties = default!;
if (varieties.Any(e => e.Equals("Grapes")))
{
    //Perform some operation
}
Run Code Online (Sandbox Code Playgroud)

尽管下面满足预期的 if 条件,但我不想硬编码为varieties[0].

if (varieties[0].ToString() == "Grapes")
{
    //Perform some operation

}
Run Code Online (Sandbox Code Playgroud)

我可以知道检查这个的正确条件吗?谢谢。

Tim*_*ter 7

枚举不是字符串,因此不会返回true

varieties.Any(e => e.Equals("Grapes"))
Run Code Online (Sandbox Code Playgroud)

你要:

if (varieties.Any(e => e == Type.Grapes))
{
    //Perform some operation

}
Run Code Online (Sandbox Code Playgroud)

旁注:枚举名称Type不是一个好主意,因为它与System.Type.