Reputation: 23
is it possible in some way to compare multiple variables to one constant in a if statement? It would be very helpful if instead of
if ( col.Name != "Organization" && col.Name != "Contacts" && col.Name != "Orders" ) { }
I could just say
if ( col.Name != "Organization" || "Contacts" || "Orders" ) { }
And I know I could use a list but in some instances I dont want to... Thanks!
Upvotes: 2
Views: 311
Reputation: 4466
I second John's comment on extension methods. I'd do something like this:
public static class StringExtensions
{
public static bool In(this string input, params string[] test)
{
foreach (var item in test)
if (item.CompareTo(input) == 0)
return true;
return false;
}
}
You can then call it like this:
string hi = "foo";
if (hi.In("foo", "bar")) {
// Do stuff
}
Upvotes: 1
Reputation: 1094
You could also add extension methods to the string class to make your comparisons less verbose. I'd go with the solution Anthony provides and stick it in an extension methods called EqualsAny or some such.
Upvotes: 1
Reputation: 126892
If you're just looking for a shortcut, you probably won't get much. ChaosPandion mentioned the switch statement, and here's something using an array.
if (new string[] { "Bar", "Baz", "Blah" }.Contains(foo))
{
// do something
}
Upvotes: 5
Reputation: 78282
The switch statement is about as good as you'll get.
switch (col.Name)
{
case "Organization":
case "Contacts":
case "Orders":
break;
default:
break;
}
Upvotes: 4