Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplify if(x == 1 || x == 2) [duplicate]

Tags:

c#

Possible Duplicate:
C# if statements matching multiple values

I often find myself writing code where a variable can be either A or B, for example when I call OnItemDataBound on a repeater:

protected void repeater_OnItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {}
}

I then often think, there must be a simpler way of doing this. I would like to write something like:

if(x == (1 || 2))

SQL has the IN(..) operator, is there something similar in C#?

WHERE x IN(1,2)

I know I could use a switch-statement instead, but thats not simple enought. I want it to be done in an If statement, if possible.

like image 972
Jimmy Mattsson Avatar asked Jan 05 '12 13:01

Jimmy Mattsson


2 Answers

I think it is fine as-is; however, you could do something like:

// note the array is actually mutable... just... don't change the contents ;p
static readonly ListItemType[] specialTypes =
     new[]{ListItemType.Item, ListItemType.AlternatingItem};

and check against:

if(specialTypes.Contains(e.Item.ItemType)) {
    // do stuff
}

But to emphasise: I'd actually just use a switch here, as switch on integers and enums has special IL handling via jump-tables, making it very efficient:

switch(e.Item.ItemType) {
    case ListItemType.Item:
    case ListItemType.AlternatingItem:
       // do stuff
       break;
}
like image 82
Marc Gravell Avatar answered Sep 30 '22 23:09

Marc Gravell


You could write an extension method like this:

public static bool In<T>(this T x, params T[] values)
{
  return values.Contains(x);
}

And call it like this:

1.In(2,3,4)

But I would say it's not worth the effort.

like image 25
void Avatar answered Sep 30 '22 22:09

void