How to simplify this comparison?

Asked

Viewed 171 times

4

I often fall into the following situation :

For example in c#:

string variavel= "x";

boolean b = (variavel == "a" || variavel == "d" ||.....|| variavel== "y");

Is there any way to simplify something like b =("a" || "b" || .... ||" y")?

In addition to being annoying I think it will greatly improve readability if there is something similar. Switch case does not help much .

  • Yes use in_array() ;)

  • 10

    You need to choose a language, the way to solve the problem changes from one to another.

  • Thanks rray , the intention to know how you solve this situation on a daily basis. The solution of the array is great ! I don’t understand why languages in general don’t come with something intuitive like an operator |= "a'',"b","c"

  • 2

    In C#, using LINQ, you can do the following: bool b = new string[] {"a", "b", ...}.Any(s => s == variavel);

3 answers

6


In C# you can do the following, using LINQ:

bool b = new string[] {"a", "b", ...}.Any(s => s == variavel);

Behold here an example of the code.

  • Excellent !! Thank you very much Omni !

  • by creating a vector this does not compromise the performance?

  • @Pilati depends on how the comparison occurs. In illustrative terms, the vector is perfectly acceptable. In an application where the comparison is always against the same vector, the solution would be to create the vector once and use it in subsequent comparisons. But as said depends on the specific case of the OP (that is not given to understand in the question).

2

In C, if "strings" are just characters, I would use strchr()

char *b;
char variavel[100] = "x";
b = strchr("ad...y", *variavel);
// usa b como boolean
if (b) ok();

If strings are actually strings of 0 or more characters, you would choose a sequence of ifs chained

char variavel[100] = "XPTO";
if (strcmp(variavel, "AAAA") == 0) ok();
else if (strcmp(variavel, "DDDD") == 0) ok();
else if (strcmp(variavel, "....") == 0) ok();
else if (strcmp(variavel, "YYYY") == 0) ok();

1

I can’t think of an alternative to successive comparisons. The best thing to do would be to put each comparison on a different line as in the case below, but only improve visibility:

bool b = (
    variavel == "a" ||
    variavel == "b" ||
    ...             ||
    variavel == "y"
)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.