简体   繁体   English

将多个复选框值添加到标签,基于它们是否被选中C#

[英]Adding up Multiple Checkbox values to a label, Based on if they are Checked or notC#

Alright I have 8-10 check boxes and radio buttons, and i need to sum up the double values that are assigned to them.好吧,我有 8-10 个复选框和单选按钮,我需要总结分配给它们的双精度值。 The only problem is that I only want to check some of the boxes not all of them.唯一的问题是我只想检查一些框而不是全部。 If you could help me out that would be great.如果你能帮助我,那就太好了。 Also any pointers on my code will also 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 to see if the check boxes are checked.我正在使用 if 语句来查看是否选中了复选框。 I need a way to add them all up depending on if they are 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 this version as a 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: TotalOrderCost 的 LINQ 版本:

    public double TotalOrderCost()
    {
        return mapping.Where(keyValuePair => keyValuePair.Key.Checked).Sum(keyValuePair => keyValuePair.Value);
    }

You can add more comboboxes without modifiing the code multiple places.您可以添加更多组合框,而无需在多个位置修改代码。

This should help.这应该有帮助。 I wrote a simple Console Application to demonstrate how to do this.我编写了一个简单的控制台应用程序来演示如何执行此操作。 It looks a lot more complicated than it is, and that is only because I had to put extra stuff in there to simulate a Sql or what ever you might be using.它看起来比实际复杂得多,这只是因为我不得不在其中添加额外的东西来模拟 Sql 或您可能使用的任何东西。 I would just focus on the Food class and the Ingredient class.我只会专注于食品类和成分类。 How they are set up mainly.它们主要是如何设置的。 Also, take a look at the bottom of the static void main to see how I called the methods that I made in the food class.另外,看看 static void main 的底部,看看我如何调用我在食品类中创建的方法。 I have updated this with regions and comments to make it easier to read.我已经用区域和评论更新了它,以使其更易于阅读。

class Program
{
    static void Main(string[] args)
    {

        #region SimulatedDb
        // Technically a Food object from the Database

        var myFood = new Food() { Name = "Sub", Ingredients = new List<IngredientViewModel>(), Price = 8.00 };

        // Technically Ingredients from the Database

        var cbSpringMixIn = new Ingredient() { Name = "Spring Mix", Price = 2.00 };
        var cbAvacodoIn = new Ingredient() { Name = "Avacodo", Price = 1.50 };
        var cbBeansIn = new Ingredient() { Name = "Beans", Price = 2.00 };
        #endregion

        // This would actually be in your code
        // You would probably just do a for each statement to turn all of these into 
        // Objects and add them to the list of available ingredients

        var cbSpringMix = new IngredientViewModel(cbSpringMixIn);
        var cbAvacodo = new IngredientViewModel(cbAvacodoIn);
        var cbBeans = new IngredientViewModel(cbBeansIn);

        #region SimulatedUserInterface
        Console.WriteLine("What would you like on your {0} ({1:C})", myFood.Name, myFood.Price);
        Console.WriteLine();
        Console.WriteLine("Would you like {0} ({1:C})", cbSpringMix.Name, cbSpringMix.Price);
        Console.WriteLine("yes or no");
        var answer = Console.ReadLine();
        if (answer == "yes")
        {
            cbSpringMix.Selected = true;
        }
        Console.WriteLine();
        Console.WriteLine("Would you like {0} ({1:C})", cbAvacodo.Name, cbAvacodo.Price);
        Console.WriteLine("yes or no");
        var answer1 = Console.ReadLine();
        if (answer1 == "yes")
        {
            cbAvacodo.Selected = true;
        }
        Console.WriteLine();
        Console.WriteLine("Would you like {0} ({1:C})", cbBeans.Name, cbBeans.Price);
        Console.WriteLine("yes or no");
        var answer2 = Console.ReadLine();
        if (answer2 == "yes")
        {
            cbBeans.Selected = true;
        }
        #endregion

        // This would actually be in your code
        // You would probably just do a for each statement to turn all of these into 
        // Objects and add them to the list of available ingredients

        myFood.Ingredients.Add(cbAvacodo);
        myFood.Ingredients.Add(cbBeans);
        myFood.Ingredients.Add(cbSpringMix);

        #region SimulatedUserInterfaceContinued

        Console.WriteLine("You are ready to check out! Press any key to continue...");
        var checkout = Console.ReadLine();

        Console.Write("You have ordered a {0} with ", myFood.Name);
        foreach (var ingredient in myFood.GetSelectedNames())
        {
            Console.Write(ingredient + " ");
        }
        Console.WriteLine();

        Console.WriteLine("Your Final Price is:");
        Console.WriteLine(String.Format("{0:C}", myFood.GetFullPrice()));
        Console.ReadLine();
        #endregion


    }
    public class Food
    {
        public Food()
        {

        }
        public IEnumerable<string> GetSelectedNames()
        {
            return (
                from f in this.Ingredients
                where f.Selected
                select f.Name).ToList();
        }
        public IEnumerable<double> GetSelectedValues()
        {
            return (
                from f in this.Ingredients
                where f.Selected
                select f.Price).ToList();
        }
        public double GetFullPrice()
        {
            var selectedIngredients = GetSelectedValues();
            return selectedIngredients.Sum() + this.Price;
        }
        public string Name { get; set; }
        public double Price { get; set; }

        public virtual List<IngredientViewModel> Ingredients { get; set; }

    }
    public class IngredientViewModel
    {
        public IngredientViewModel(Ingredient ingredient)
        {
            this.Name = ingredient.Name;
            this.Price = ingredient.Price;
            this.Selected = false;
        }
        public string Name { get; set; }
        public double Price { get; set; }
        public bool Selected { get; set; }

    }
    public class Ingredient
    {
        public string Name { get; set; }
        public double Price { get; set; }

    }


}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM