Are multiple C # comparisons possible?
Is it possible in some way to compare multiple variables with the same constant in an 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 can use a list, but in some cases I don't want to ... Thanks!
+2
a source to share
4 answers
Second, John comments on extension methods. I would 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;
}
}
Then you can call it like this:
string hi = "foo";
if (hi.In("foo", "bar")) {
// Do stuff
}
+1
a source to share