Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a concise way to check if an int variable is equal to a series of ints? | C#

Tags:

c#

Rather than something like this:

switch (id) {
case 2:
case 5:
case 11:
case 15:
...
}

Is there a concise way to check if an int variable is equal to any one of a series of integers? Maybe something like if (id == {2|5|11|15}) ...?

like image 439
Chaddeus Avatar asked Dec 09 '22 09:12

Chaddeus


2 Answers

You could put all the ints into a HashSet and do a contains.

Hashset<int> ids = new HashSet<int>() {...initialize...};

if(ids.Contains(id)){
...
}
like image 66
Craig Suchanec Avatar answered Dec 11 '22 22:12

Craig Suchanec


if((new List<int> { 2, 5, 11, 15}).Contains(id))

But you probably don't want to create a new List instance every time, so it would be better to create it in the constructor of your class.

like image 44
Daniel Hilgarth Avatar answered Dec 11 '22 23:12

Daniel Hilgarth