如果声明与数组

时间:2017-01-20 03:14:37

标签: c# console-application

有没有办法做类似下面的事情?

,而不是编写多个if()语句
string redlight = "Larry";
string[] names = { "Joe", "Jack", "Bob", "Larry", "Alpha", "Mick", "Lance", "Ben" };

if (redlight == names)
    Console.WriteLine("It's in the array");

1 个答案:

答案 0 :(得分:2)

您可以使用.Contains()

if (names.Contains(redlight))
    Console.WriteLine("It's in the array");
else
    Console.WriteLine("It's not in the array");

.Any()

if (names.Any(x=>x==redlight))
   Console.WriteLine("It's in the array");
else
   Console.WriteLine("It's not in the array");

结帐Working example