KMC
KMC

Reputation: 20046

How to apply multiple operands to a single operator?

How to apply multiple operands to a single operator?

An example:

instead of

if (foo == "dog" || foo == "cat" || foo == "human")

I can have the following or similar:

if (foo == ("dog" || "cat" || "human"));

Upvotes: 5

Views: 728

Answers (4)

skywalker
skywalker

Reputation: 23

You can always try it out, compile and see for yourself :)

("dog" || "cat" || "human")

is not a meaningful expression for C#

Maybe you can put them in an array and loop over them.

Or better still, put them in an array and come up with a cool lambda expression.

Upvotes: 0

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48568

Use switch case

switch(foo)
{
   case "dog":
   case "cat":
   case "human":
   //Your Code
   break;
}

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500525

Your first version already includes multiple operators in one expression. It sounds like you want to apply multiple operands ("dog", "cat", "human") to a single operator (== in this case).

For that specific example you could use:

// Note: could extract this array (or make it a set etc) and reuse the same
// collection each time we evaluate this.
if (new[] { "dog", "cat", "human" }.Contains(foo))

But there's no general one-size-fits-all version of this for all operators.

EDIT: As noted in comments, the above won't perform as well as the hard-coded version.

Upvotes: 9

Tigran
Tigran

Reputation: 62246

Can do something like this:

List<string> values = new List<string> {"dog", "cat", "human"}; 
values.Any(s=>s.Equals(foo ));

But in my opinion the code you written is already more readable then any other solution. If we are not talking here about of possible dozens of options, naturally.

Upvotes: 1

Related Questions