2017-01-20 6 views
0

if()ステートメントを複数記述するのではなく、以下のような方法がありますか?Ifステートメントで配列

string redlight = "Larry"; 
string[] names = { "Joe", "Jack", "Bob", "Larry", "Alpha", "Mick", "Lance", "Ben" }; 

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

'ここredlight'されているもの? –

+0

文字列変数、 –

+3

'if(names.Contains(redlight))' – Hendry

答えて

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

+0

xが.Any()の例で表すもの –

+1

これはコレクションを内部的に反復するので、 'x'はコレクションのアイテムになります。' .Any() '[ここ]から(https://msdn.microsoft.com/en-us/library/bb534972(v=vs.110)asp) –

関連する問題