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.
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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With