IF Statement multiple conditions, same statement

前端 未结 10 2024
孤城傲影
孤城傲影 2021-02-02 12:23

Hey all, looking to reduce the code on my c# if statements as there are several repeating factors and was wondering if a trimmer solution is possible.

I currently have 2

相关标签:
10条回答
  • 2021-02-02 12:49

    Pretty old question but check this for a more clustered way of checking conditions:

    private bool IsColumn(string col, params string[] names) => names.Any(n => n == col);
    

    usage:

    private void CheckColumn()
    {
         if(!IsColumn(ColName, "Column A", "Column B", "Column C"))
        {
         //not A B C column
        }
    
    }
    
    0 讨论(0)
  • 2021-02-02 13:01

    How about maybe something like this?

        var condCheck1 = new string[]{"a","b","c"};
        var condCheck2 = new string[]{"a","b","c","A2"}
    
        if(!condCheck1.Contains(columnName) && !checkbox.checked)
            //statement 1
        else if (!condCheck2.Contains(columnName))
            //statment 2
    
    0 讨论(0)
  • 2021-02-02 13:03
    if (columnname != a && columnname != b && columnname != c 
            && (columnname != A2 || checkbox.checked))
        {
          "statement 1"
        }
    
    0 讨论(0)
  • 2021-02-02 13:03

    I always try to factor out complex boolean expressions into meaningful variables (you could probably think of better names based on what these columns are used for):

    bool notColumnsABC = (columnname != a && columnname != b && columnname != c);
    bool notColumnA2OrBoxIsChecked = ( columnname != A2 || checkbox.checked );
    
    if (   notColumnsABC 
        && notColumnA2OrBoxIsChecked )
      {
          "statement 1"
      }
    
    0 讨论(0)
  • 2021-02-02 13:05
    if (columnname != a 
      && columnname != b 
      && columnname != c
      && (checkbox.checked || columnname != A2))
    {
       "statement 1"
    }
    

    Should do the trick.

    0 讨论(0)
  • 2021-02-02 13:05

    Isn't this the same:

    if ((checkbox.checked || columnname != A2) && 
            columnname != a && columnname != b && columnname != c)
      {
          "statement 1"
      }
    
    0 讨论(0)
提交回复
热议问题