Arif YILMAZ
Arif YILMAZ

Reputation: 5866

any way to compare an integer variable to a list of integers in if statement

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

Upvotes: 1

Views: 3365

Answers (5)

Adam Houldsworth
Adam Houldsworth

Reputation: 64487

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

Upvotes: 0

Mohammed Swillam
Mohammed Swillam

Reputation: 9242

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

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726599

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.

Upvotes: 8

Markus
Markus

Reputation: 22456

int[] intArray = { 1, 2, 3, 4, 5 };
if (intArray.Contains(3))
        // ...

Upvotes: 1

Esteban Elverdin
Esteban Elverdin

Reputation: 3582

Try this:

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

if (numbers.Contains(myId))
{
}

Upvotes: 3

Related Questions