0

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");
9
  • what is redlight here? Commented Jan 20, 2017 at 3:15
  • string variable, let me edit Commented Jan 20, 2017 at 3:16
  • 3
    if (names.Contains(redlight)) Commented Jan 20, 2017 at 3:16
  • How strict do you need to be? if redlight = "joe", do you want to match "Joe" in the array? Commented Jan 20, 2017 at 3:17
  • 2
    Possible duplicate of How to search a string in String array Commented Jan 20, 2017 at 3:20

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

What does x represent in the .Any() example
It will internally iterate the collection so x will be an item of the collection, you can read more about .Any() from here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.