Firedan1176
Firedan1176

Reputation: 691

C# - Simpler/Shorter way to make an 'if-or' statement

Is there any way to shorten this statement:

if(string.Equals("Hello") || string.Equals("Hi") || string.Equals("Hey")) { }

To something like:

if(string.Equals("Hello" || "Hi" || "Hey")) { }

It's not necessary, but can be handy.

Upvotes: 0

Views: 55

Answers (2)

Kiran Paul
Kiran Paul

Reputation: 885

if ((new List<string> { "Hello", "Hi", "Hey" }).Contains(yourValue))
{
//your code here 
}

Here I created a list of strings with values Hello, Hi and Hey. Then I am just searching whether the value of variable yourValue is present in the created list.

Upvotes: 0

Firedan1176
Firedan1176

Reputation: 691

Thanks to @thelaws who suggested using an array of the possible values and flipping the statement, which I got to work with:

if(new string[]{"Hello", "Hi", "Hey"}.Contains(value)) { }

Upvotes: 1

Related Questions