Home > OS >  How can I shorten the "if else" event?
How can I shorten the "if else" event?

Time:03-04

how can I Write this as short as possible? here are many more conditions. The purpose of the code below is to calculate the total price and display it as a message, adding the price of each selected hardware to the determined base price to the Calculate button click event.

( sorry for bad english :/ )

decimal tabanFiyat = 500;
decimal cpuFiyat = 0;

if (rbCpuI7.Checked)
  cpuFiyat = 300;
else if (rbCpuI5.Checked)
  cpuFiyat = 200;
else if (rbCpuI3.Checked)
  cpuFiyat = 100;
else if (rbCpuR5.Checked)
  cpuFiyat = 250;
else if (rbCpuR3.Checked)
  cpuFiyat = 150;

tabanFiyat  = cpuFiyat;

decimal ramFiyat = 0;

if (rbRam16.Checked)
  ramFiyat = 125;
else if (rbRam8.Checked)
  ramFiyat = 75;
else if (rbRam4.Checked)
  ramFiyat = 45;

tabanFiyat  = ramFiyat;

CodePudding user response:

I think this can work:

cpuFiyat = (rbCpuI7.Checked)? 300: 
           (rbCpuI5.Checked)? 200:
           (rbCpuI3.Checked)? 100:
           (rbCpuR5.Checked)? 250:
           (rbCpuR3.Checked)? 150: 0;

tabanFiyat  = cpuFiyat;
decimal ramFiyat;
ramFiyat = (rbRam16.Checked)? 125:
           (rbRam8.Checked)?   75:
           (rbRam4.Checked)?   45: 0;

tabanFiyat  = ramFiyat;

CodePudding user response:

Assuming those are radio buttons

  var radList = new List<(RadioButton, int)> {
      (rbCpuI7,300),
      (rbCpuI5,200)
      .....
   };

   var chck = radList.FirstOrDefault(x=>x.Item1.Checked);
   rbCpuI5  = chk.Item2;

if nothing is checked you will get 0

CodePudding user response:

Assuming the .Checked property comes from some UI, the framework is likely to expose an "onChecked" event so the event handler should assign the correct value, and uncheck others if mutually exclusive. But you'd need to provide more details.

  •  Tags:  
  • c#
  • Related