Alan2
Alan2

Reputation: 24572

Is there a shortcut with switch expressions for multiple values to give the same result?

Here's the code that I have now:

        var pageTitleFont = Settings.Fs switch
        {
            140 => 1.1,
            130 => 1.1,
            120 => 1.1,
            110 => 1.1,
            100 => 1,
            90 => 0.9,
            _ => 1
        };

What I would like to do is to reduce the need for having the same entries for 110,120,130 and 140. Is there any way to shortcut this?

Upvotes: 0

Views: 125

Answers (2)

Michał Turczyn
Michał Turczyn

Reputation: 37367

You could split your number into hunderds and tens and base logic upon that.

Then switch expression becomes really concise:

var test = Enumerable.Range(5, 12).Select(i => i * 10).ToArray();
foreach (int i in test)
{
    var hundreds = i / 100;
    var tens = (i % 100) / 10;
    var result = (hundreds == 1, tens < 5, tens > 0, tens == 9) switch
    {
      (true, true, true, false) => 1.1,
      (false, false, true, true) => 0.9,
      (_, _, _, _) => 1,
    };
    Console.WriteLine($"{i} => {result}");
}

But note that, you approach is very clear and readable.

My suggestion is REALLY ONLY in terms of being concise, it's not much readable and any changes to logic might be terrible.

But on the other hand, in some cases might become very handy.

Upvotes: 1

Sean
Sean

Reputation: 62492

You can use a when condition:

var pageTitleFont = Settings.Fs switch
{
    var x when x == 110 || x == 120 || x == 130 || x == 140 => 1.1,
    100 => 1,
    90 => 0.9,
    _ => 1
};

Upvotes: 3

Related Questions