Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Multi-Comparisons possible?

Tags:

c#

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!

like image 334
Iggy Ma Avatar asked Jan 19 '26 01:01

Iggy Ma


2 Answers

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
}
like image 153
Anthony Pegram Avatar answered Jan 21 '26 14:01

Anthony Pegram


The switch statement is about as good as you'll get.

switch (col.Name)
{
    case "Organization":
    case "Contacts":
    case "Orders":
        break;
    default:
        break;
}
like image 31
ChaosPandion Avatar answered Jan 21 '26 13:01

ChaosPandion



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!