C#. Do if( a == (b or c or d)). Is it possible?

前端 未结 11 1627
无人及你
无人及你 2021-02-02 09:31

Is there another way to write something like this:

if (a == x || a == y || a == z)

One way that I found is doing it like this:

         


        
相关标签:
11条回答
  • 2021-02-02 10:09

    Your solution to rewrite it as

    if( new [] {x,y,z}.Contains(a))
    

    is not a good move.

    You've take a simple efficient logical operation, which every programmer easily understands and which contains short-circuiting logic to speed it up and instead you've produced code that requires a moment to understand and which is considerably less efficient.

    Sometimes your fellow engineers will prefer it if you don't try to be "clever"!

    0 讨论(0)
  • 2021-02-02 10:10
    if(a==x?true:a==y?true:a==z?true:false)
    
    0 讨论(0)
  • 2021-02-02 10:10

    For instance, your logic is like that:

    if(a==x || a== y|| a==z)
    {
        DoSomething();
    } 
    else
    {
       DoOtherThings();
    }
    

    will equivalent to:

    if(a!=x&& a != y && a!= z)
    {
       DoOtherThings();
    }
    else
    {
       DoSomething();
    }
    

    Cheers.

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

    Consider a case where a == x, and y and z are slow-to-evaluate, expensive functions.

    • In if(a == x || a == y || a == z) you have the benefit of the short-circuit ||-operator, so you y and z won't be evaluated.
    • If you make an array with new[] { x, y, z } - y and z will be evaluated every time.

    The 'trick' with .Contains() would be more useful if there was an elegant syntax to create lazy-evaluated sequence (IEnumerable<T>). i.e. something like yield return x; yield return y;..., but inlined and shorter.

    0 讨论(0)
  • 2021-02-02 10:19

    Why would you need yet another way? Since it isn't a matter of functionality, I would guess the point is to improve readability. If you have a few variables with meaningful names, it would be more readable to just compare by using ==. If you have more, you can use Contains against a list as in your other sample. Yet another way would be comparing against enum flags:

    [Flags]
    public enum Size
    {
        Small = 1,
        Medium = 2,
        Large = 4
    }
    

    And then to find out if mySize is in Small or Medium:

    selectedSizes = Size.Small | Size.Medium;
    mySize = Size.Small;
    if (mySize & selectedSizes)
    {
      ... 
    }
    
    0 讨论(0)
提交回复
热议问题