asdsad asdsad - 1 month ago 6
C# Question

How would I make something like a switch statement, but for multiple conditions

private bool test(int x, int y, int z)
{
int[] arr = {x,y,z};
switch (arr)
{
case {4,5,6}:
return true;
case {1,2,3}:
return true;
case {7,8,9}:
return true;
default:
return false;
}
}


Essentially, I want to create a function that does this. However, you cannot use an array value inside a switch statement. How would I accomplish something like this? I don't really want to do a bunch of if statements, there will be around ~300 possible combinations.

For further clarification, the function will always return true if it finds a case, and returns false if it doesn't find a case. (Order matters)

One possible solution is I convert the x y z value to a string, of "x y z" then have a case of ~300 string values. But that seems pretty hacky.

Answer Source

Use a HashSet to facilitate the valid combinations. Then searching if a given x,y,z combination in it is done using Contains and as it is a HashSet takes O(1):

HashSet<(int a, int b, int c)> options = new HashSet<(int a, int b, int c)>
{
    (4,5,6),
    (1,2,3),
    (7,8,9),
    // ... the rest of the cases
};

options.Contains((x, y, z));

For pre C# 7.0 use:

HashSet<Tuple<int, int, int>> options = new HashSet<Tuple<int, int, int>>
{
    Tuple.Create(4,5,6),
    Tuple.Create(1,2,3),
};

options.Contains(Tuple.Create(x, y, z));

Do note that having 300 cases hard coded (or any number of cases hard coded) isn't a good practice. I suggest rethink how you store these values. You can store them in a database or configuration file and load them. Then after loading store in the HashSet as I suggested.


As for the switch case notice that if you have the same behavior for different cases you can:

switch (caseSwitch) {
    case 1:
    case 2:
    case 3:
    case 4:
        return true;
    default:
        return false;
}