1

I am wondering if there is a way to compare an integer variable to a list of integers in if statement as we can do it in SQL WHERE CLAUSE,

WHERE MY_ID IN (1,2,3,4,5,6)

and I want to use the same functionality if it exists in c#

if(myid in (1,2,3,4,5,6)){}

this might seem a dummy question but it would save me a lot of time if existed

Arif YILMAZ
  • 5,754
  • 26
  • 104
  • 189

5 Answers5

8

You can use an array aggregate directly in your if statement, like this:

if (new[] {1,2,3,4,5,6}.Contains(id)) {
}

Note: you need to add using System.Linq in order for this to compile.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
3

Try this:

var numbers = new List<int>() {1,2,3,4,5,6};

if (numbers.Contains(myId))
{
}
Esteban Elverdin
  • 3,552
  • 1
  • 17
  • 21
1
int[] intArray = { 1, 2, 3, 4, 5 };
if (intArray.Contains(3))
        // ...
Markus
  • 20,838
  • 4
  • 31
  • 55
0

Alternatively to List<T>.Contains, if you want to do this to keep a track of values you have already entered, you could use HashSet<int> as the Add methods returns true if the value is added:

var numbers = new HashSet<int>();

if (numbers.Add(myNumber))
{
    // myNumber has just been inserted into numbers
}

The HashSet also has the added benefit of being designed to quickly find specific values inside it based on hash, and with int, the hash is simply the int itself.

And it has Contains:

if (numbers.Contains(myNumber))
{}

IEnumerable also has a Contains extension method for anything else:

http://msdn.microsoft.com/en-us/library/system.linq.enumerable.contains(v=vs.110).aspx

Adam Houldsworth
  • 63,413
  • 11
  • 150
  • 187
0

using the Contains Extension method you can achieve this eaisly:

var myNumberList = new List<int>(){1,2,3,4};

// check using the Contains extension method

if(myNumberList.contains(TARGET_NUMBER))
{
 // do your stuff here
}

from the official MSDN article:

Determines whether a sequence contains a specified element by using the default equality comparer.

Link: http://msdn.microsoft.com/en-us/library/bb352880.aspx

Mohammed Swillam
  • 9,119
  • 4
  • 36
  • 47