c# - Adding up Multiple Checkbox values to a label, Based on if they are Checked or notC# -


alright have 8-10 check boxes , radio buttons, , need sum double values assigned them. problem want check of boxes not of them. if me out great. pointers on code help

    double springmix = 2.00;     double avocado = 1.50;     double beans = 2.00;     double cheese = 2.00;     double tomato = 1.50;     double honeymustard = 2.00;     double ranch = 2.00;     double italian = 2.00;     double bluecheese = 2.00;      double foodcost; 

i'm using if statements see if check boxes checked. need way add them depending on if checked.

public double totalordercost()     {         if (cbspringmix.checked)         {             foodcost + 2.00;         }         if (cbavocado.checked)         {             foodcost + 1.50;         }         if (cbbeans.checked)         {             foodcost + 2.00;         }         if (cbcheese.checked)         { 

i have version solution:

    private readonly dictionary<checkbox, double> mapping;      public mainwindow()     {         initializecomponent();         mapping = new dictionary<checkbox, double>         {             {cbbean, 2d},             {cbspringmix, 2d}             //...         };     }      public double totalordercost()     {         double foodcost = 0d;         foreach (keyvaluepair<checkbox, double> keyvaluepair in mapping)         {             if (keyvaluepair.key.checked)             {                 foodcost += keyvaluepair.value;             }         }         return foodcost;     } 

linq version of totalordercost:

    public double totalordercost()     {         return mapping.where(keyvaluepair => keyvaluepair.key.checked).sum(keyvaluepair => keyvaluepair.value);     } 

you can add more comboboxes without modifiing code multiple places.


Comments

Popular posts from this blog

unity3d - Rotate an object to face an opposite direction -

angular - Is it possible to get native element for formControl? -

javascript - Why jQuery Select box change event is now working? -