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


If you're just looking for a shortcut, you probably won't get much. ChaosPandion mentions a switch statement and something uses an array here.



if (new string[] { "Bar", "Baz", "Blah" }.Contains(foo))
{
    // do something
}

      

+5


a source


The switch statement is about as good as you are.



switch (col.Name)
{
    case "Organization":
    case "Contacts":
    case "Orders":
        break;
    default:
        break;
}

      

+5


a source


You can also add extension methods to the string class to make comparisons less verbose. I would go with the solution Anthony suggests and stick with it in the EqualsAny extension methods or some such.

+1


a source


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







All Articles