【问题标题】:Operators in C#: Is there something like the "IN" operator in SQL Server?C# 中的运算符:SQL Server 中有类似“IN”运算符的东西吗?
【发布时间】:2014-08-22 22:26:16
【问题描述】:

我在 C# 代码隐藏中有这个语句,我正在检查我的变量是否等于特定数字,如果是,它将处理一些代码:

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);
}

完美运行。但是,现在我想在“如果”列表中添加一些其他数字。在 SQL Server 中,它会是这样的:

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

有没有办法在 C# 中做到这一点?我还在学习,所以如果这有点简单,我很抱歉。

【问题讨论】:

    标签: c# operators code-behind


    【解决方案1】:

    您可以将项目的集合(例如数组)与来自 LINQ 的 Contains() 一起使用:

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

    【讨论】:

      【解决方案2】:

      只写:

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

      不要忘记添加以下参考:

      using System.Linq;
      

      【讨论】:

      • 仅供参考,您不需要指定数组的类型,因为它可以被推断出来(new[] {... vs new int[] {...)。
      • 这和 svick 的答案都很完美,我给了这个答案,因为它更完整一点。谢谢!
      【解决方案3】:

      您还可以使用switch 语句,这将允许其他可能性:

      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;
      }
      

      【讨论】:

        猜你喜欢
        • 2012-12-15
        • 1970-01-01
        • 2011-03-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多