IF Statement multiple conditions, same statement

前端 未结 10 2025
孤城傲影
孤城傲影 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 13:06

    You could also do this if you think it's more clear:

    if (columnname != a 
      && columnname != b 
      && columnname != c
    {
       if (checkbox.checked || columnname != A2)
       {
          "statement 1"
       }
    }
    
    0 讨论(0)
  • 2021-02-02 13:08
    var test = new char[] {a, b, c}.Contains(columnname));
    
    if(test)
    {
      "true statement"
    }
    else
    {
       "false statement"
    }
    
    0 讨论(0)
  • 2021-02-02 13:10
    if (checkbox.checked && columnname != a && columnname != b && columnname != c)
        {
          "statement 1"
        }
    else if (columnname != a && columnname != b && columnname != c 
            && columnname != A2)
        {
          "statement 1"
        }
    

    is one way to simplify a little.

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

    I think agileguy has the correct answer, but I would like to add that for more difficult situations there are a couple of strategies I take to solve the problem. The first is to use a truth table. If you Google "truth table" you will run across some examples related directly to programming and computer science.

    Another strategy I take is to use an anonymous function to encapsulate common logic between various conditions. Create it right before the if block, then use it where needed. This seems to create code that is more readable and maintainable.

    0 讨论(0)
提交回复
热议问题