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

前端 未结 6 706
野的像风
野的像风 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条回答
  •  旧时难觅i
    2021-01-20 01:18

    You could use an extension method:

    public static class ExtensionMethods
    {
        public static bool EqualsAny(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)) 
    {
        // ...
    }
    

提交回复
热议问题