Ternary operator for 3 conditions

224 Views Asked by At

I have using jsReport lib in different enviroments (Windows, OsX and Linux)

In Startup.cs I use this code, to launch library

services.AddJsReport(new LocalReporting()
                .UseBinary(RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
                    ? JsReportBinary.GetBinary()
                    : jsreport.Binary.OSX.JsReportBinary.GetBinary()).AsUtility()
            .Create());

So if it's not Windows platform, he looking for binary for OSX.

But when somebody will use project on Linux he need to change code to:

services.AddJsReport(new LocalReporting()
            .UseBinary(RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
                ? JsReportBinary.GetBinary()
                : jsreport.Binary.Linux.JsReportBinary.GetBinary())

How I can write ternary condition for using Windows as main, and if not it will select between OSX and Linux?

3

There are 3 best solutions below

1
MindSwipe On
services.AddJsReport(new LocalReporting()
    .UseBinary(
        RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
        ? JsReportBinary.GetBinary()
        : RuntimeInformation.IsOSPlatform(OSPlatform.Linux)
            ? Jsreport.Binary.Linux.JsReportBinary.GetBinary()
            : Jsreport.Binary.OSX.JsReportBinary.GetBinary())
    .Create();

But it might be easier just writing 3 ifs and doing it like so:

// I don't know the exact type, put the correct one here if it isn't this
JsReportBinary binary;

if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
    binary = JsReportBinary.GetBinary();
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
    binary = Jsreport.Binary.Linux.JsReportBinary.GetBinary();
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)
    binary = Jsreport.Binary.OSX.JsReportBinary.GetBinary());
else
    binary = null;

services.AddJsReport(new LocalReporting().UseBinary(binary).Create());
0
Salah Akbari On

You can do something like this:

RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
      ? JsReportBinary.GetBinary() :
    RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ?
   jsreport.Binary.OSX.JsReportBinary.GetBinary()  : 
   jsreport.Binary.Linux.JsReportBinary.GetBinary())
0
Sushant Yelpale On

I have not tested it, but it will work,

services.AddJsReport(new LocalReporting()
                .UseBinary((RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && JsReportBinary.GetBinary())
                           || (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && Jsreport.Binary.Linux.JsReportBinary.GetBinary())
                           || (Jsreport.Binary.OSX.JsReportBinary.GetBinary()))
                .Create();

Benefit: we can have any number of conditions.