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
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))
{
// ...
}
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 ) );
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)
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!");
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.
if (new [] {State.CT, State.MA, State.VA, State.RI}.Contains(myState)) {
// There you go
}