0

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?

Prasad Telkikar
  • 15,207
  • 5
  • 21
  • 44
Alan2
  • 23,493
  • 79
  • 256
  • 450
  • 3
    Does this answer your question? [c# 8 switch expression multiple cases with same result](https://stackoverflow.com/questions/56676260/c-sharp-8-switch-expression-multiple-cases-with-same-result) – Oliver Apr 02 '20 at 09:18

2 Answers2

3

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
};
Sean
  • 60,939
  • 11
  • 97
  • 136
1

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.

Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69