2

I know I can do it like this:

if(myint == 1 || myint == 2 || myint ==3) //etc...

But I feel like there must be a more efficient way to code this. Is there a way to possibly make a statement like this work?

if(myint.Contains(1 || 2 || 3 || 4))
proseidon
  • 2,235
  • 6
  • 33
  • 57

2 Answers2

14

you can do inverse

new List<int>{1,2,3,4}.Contains(myInt)

Note that there is also Enumerable.Any, but Contains would work for .net 2.0 too.

Tigran
  • 61,654
  • 8
  • 86
  • 123
8

Close, try the following.
It will take a collection and return true if your int is in the collection:

if (new[] { 1, 2, 3, 4 }.Contains(myint))
    //Do something

new[] { 1, 2, 3, 4 } represents an array of integers.

The Contains method is an extension of IEnumerable<T> and will be available to anything that implements it.

Khan
  • 17,904
  • 5
  • 47
  • 59