SmallFries BigGuys
SmallFries BigGuys

Reputation: 171

If Statement With Array

Instead of writing multiple if() statements, is there a way to do something like the below?

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

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

Upvotes: 0

Views: 8583

Answers (1)

sujith karivelil
sujith karivelil

Reputation: 29026

You can use either .Contains()

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

or .Any()

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

Checkout this Working example

Upvotes: 3

Related Questions