Обработка нескольких случаев в операторе Switch C#: методы и синтаксис

Чтобы добавить несколько регистров в новый синтаксис переключателей в C#, вы можете использовать следующие методы:

Метод 1: использование нескольких меток регистра

switch (variable)
{
    case value1:
    case value2:
        // Code to be executed when either value1 or value2 is matched
        break;
    case value3:
        // Code to be executed when value3 is matched
        break;
    default:
        // Code to be executed when no case is matched
        break;
}

Метод 2: использование выражения переключения

var result = variable switch
{
    value1 or value2 => "Result 1 or 2",
    value3 => "Result 3",
    _ => "Default Result"
};

Метод 3: объединение нескольких случаев

switch (variable)
{
    case value1:
    case value2:
    case value3:
        // Code to be executed when any of the specified values are matched
        break;
    default:
        // Code to be executed when no case is matched
        break;
}

Метод 4. Использование сопоставления с образцом

switch (variable)
{
    case int i when i > 0:
        // Code to be executed when the variable is a positive integer
        break;
    case string s when s.Length > 10:
        // Code to be executed when the variable is a string with length greater than 10
        break;
    default:
        // Code to be executed when no case is matched
        break;
}