Johnny Bones
Johnny Bones

Reputation: 8402

Operators in C#: Is there something like the "IN" operator in SQL Server?

I've got this statement in a C# code-behind where I'm checking to see if my variable is equal to a specific number, and if so it will process some code:

try
{
    int TaskID = Convert.ToInt32(ddlTask.SelectedValue);

    if (TaskID == 157)
    {
         //lblAccountName.Text = (DT1["CUST_NM"].ToString());
         Label2.Text = (DT1["CUST_NM"].ToString());
         //lblAccountName.Visible = true;
         TBAccountNum.Text = (DT1["CUST_NUM"].ToString());
         TBAccountNum.Visible = true;
     }
}
catch (Exception ae)
{
     Response.Write(ae.Message);
}

Works perfect. However, now I want to add a few other numbers to that "if" list. In SQL Server it would go something like:

if (TaskID IN (157, 158, 159, 160, 162, 165))

Is there any way to do this in C#? I'm still learning, so I apologize if this is a bit simple.

Upvotes: 2

Views: 90

Answers (3)

David Crowell
David Crowell

Reputation: 3813

You can also use a switch statement, which will allow other possibilities:

switch (taskId)
{
    case 175:
    case 176:
    case 177:
        // code for any of the values above
        break;

    case 200:
        // yet another possibility
        break;

    default:
        // any other value
        break;
}

Upvotes: 0

Seb
Seb

Reputation: 1230

just write :

if ( new int[]{157, 158, 159, 160, 162, 165}.Contains(TaskID))
    ....

Don't forget to add the following reference :

using System.Linq;

Upvotes: 5

svick
svick

Reputation: 244837

You can use a collection (e.g. an array) of items together with Contains() from LINQ:

new[] { 157, 158, 159, 160, 162, 165 }.Contains(TaskID)

Upvotes: 8

Related Questions