Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if something equals any of a list of values in C#

Tags:

c#

What is the OR operator in an IF statement

I asked this question way back when, and when I got the (very helpful) answer, I thought you should be able to say if (title == "User greeting" || "User name") {do stuff}. Now if it isn't obvious why that won't work, please refer to the other question and its accepted answer.

I am wondering, however, if there is a way to give an arbitrary list of strings to check if something equals any of them. Something like if(Array.OR(title, { "User greeting", "User name" })) continue; Is there such a thing or am I shooting in the dark? It seems like it'd be rather simple to implement.

like image 922
Arlen Beiler Avatar asked Dec 15 '22 13:12

Arlen Beiler


2 Answers

You could try the Contains operator:

String[] array = {"One", "Two", "Three"};
if (array.Contains("One"))
{
     //Do stuff       
}
like image 191
CorrugatedAir Avatar answered Jan 26 '23 00:01

CorrugatedAir


CorrugatedAir's example is pretty good, however you can include it inline if needed.

if (new string[] { "test1", "test2", "test3" }.Contains("test1")) Console.WriteLine("it works");

And it does work: http://ideone.com/QzbvKV (Thanks Soner)

So my code would look like: if (new string[] { "User greeting", "User name" }.Contains(title)) Console.WriteLine("title contained");

http://ideone.com/PYugJu

P.S. Thanks Soner for the link, I never heard of ideone before!

like image 29
Arlen Beiler Avatar answered Jan 26 '23 00:01

Arlen Beiler