Can I compress an if statement using linq in C#?

前端 未结 6 702
野的像风
野的像风 2021-01-20 01:08

In sql, I can make an if statement like the following If MY_STATE in (1,2,3,4)

In C# I have to type if(MY_STATE == STATE.CT || MY_STATE == STATE.MA || MY_STATE == ST

相关标签:
6条回答
  • 2021-01-20 01:18

    You could use an extension method:

    public static class ExtensionMethods
    {
        public static bool EqualsAny<T>(this T comparer, params T[] values)
        {
            foreach (T t in values)
                if (comparer.Equals(t))
                    return true;
    
            return false;
        }
    }
    

    and use it like:

    if (myState.EqualsAny(State.CT, State.MA, State.VA, State.RI)) 
    {
        // ...
    }
    
    0 讨论(0)
  • 2021-01-20 01:19

    You want to use Contains, which maps onto the SQL IN. I'm assuming State is an enum and stored as an integer.

    var states = new int[] { (int)State.CT, (int)State.MA, (int)State.VA, (int)State.RI };
    
    var query = db.States.Where( s => states.Contains( s.State ) );
    
    0 讨论(0)
  • 2021-01-20 01:19

    You could write your own extension method to do that:

    static bool IsOneOf<T>(this T value, params T[] set)
    {
        return set.Contains(value);
    }
    

    Usage: MY_STATE.IsOneOf(STATE_A, STATE_B, STATE_C)

    (It's slower at runtime, though. It has to create a temporary array and all parameters to IsOneOf have to be evaluated)

    0 讨论(0)
  • 2021-01-20 01:21

    You could do something like:

        enum MyEnum
        {
            A, B, C, D
        }
    
        // ...
        MyEnum e = MyEnum.A;
        if (new []{ MyEnum.A, MyEnum.B }.Contains(e))
           Console.WriteLine("Yeah!");
    
    0 讨论(0)
  • 2021-01-20 01:23

    In c++ I would use the switch statement.

    switch (MY_STATE) {
      case STATE.CT:
      case.STATE.MA:
      case.STATE.VA:
      case.STATE.RI:
        ....
        break;
    }
    

    just jotted it down from memory. So you might correct some syntax issues.

    0 讨论(0)
  • 2021-01-20 01:25
    if (new [] {State.CT, State.MA, State.VA, State.RI}.Contains(myState)) {
      // There you go
    }
    
    0 讨论(0)
提交回复
热议问题