简体   繁体   中英

Is there a way to make comparison shorter

How can I make this shorter?

string veryLongVariableName;

if (veryLongVariableName == "a" || veryLongVariableName == "b" || veryLongVariableName == "c"|| veryLongVariableName == "d"|| veryLongVariableName == "e"|| veryLongVariableName == "f")

something like this possible?

if (veryLongVariableName == ("a", "b", "c", "d", "e", "f"))
if (veryLongVariableName == ("a" || "b" || "c" || "d" || "e" || "f"))

You nearly had it

if (new [] {"a", "b", "c", "d", "e", "f"}.Contains(veryLongVariableName))

Note : This does allocate every time you call it

At risk of making your long line longer, I'd probably go with a switch here:

switch (veryLongVariableName)
{
    case "a:
    case "b:
    case "c:
    case "d:
    case "e:
    case "f:
        // your stuff 
        break;
}

(a perhaps a utility IsSomething(...) method that returns true or false on the condition, and just an if (IsSomething(...)) {...} in the code shown.

Reasons: it is clear, obvious, and efficient (no allocations; optimized by the compiler).

As an example for the IsSomething :

static bool IsSomething(string theThing) => theThing switch {
    "a" => true,
    "b" => true,
    "c" => true,
    "d" => true,
    "e" => true,
    "f" => true,
    _ => false,
};
// ...
if (IsSomething(veryLongVariableName)) { ... }

You can have all your string conditions in a List , then:

var match = myList
    .FirstOrDefault(x => x.Contains(veryLongVariableName));

if(match != null)
    //Do stuff

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM