首页 > 解决方案 > 如何更改对象类列表中的对象?

问题描述

你是可以帮助我理解对象和类的力量。

我有所有订单的清单(名称、价格和数量)。所以现在我应该检查某个项目是否在列表中出现两次或更多时间,我应该添加数量并更新最后收到的价格示例:啤酒 2.40 350 水 1.25 200 IceTea 5.20 100 Beer 1.20 200 IceTea 0.50 120 购买答案是:啤酒 -> 660.00 水 -> 250.00 冰茶 -> 110.00

using System;
using System.Collections.Generic;
using System.Linq;

{
    class Program
    {
        static void Main(string[] args)
        {List<Orders> orders = new List<Orders>();

            while (true)
            {
                string input = Console.ReadLine();
                if (input == "Buy")
                { break; }
                    string[] tokens = input.Split();
                    string product = tokens[0];
                    decimal price = decimal.Parse(tokens[1]);
                    int quantity = int.Parse(tokens[2]);
                Orders order = new Orders(product, price, quantity);
                orders.Add(order);
            }

            Console.WriteLine(String.Join(Environment.NewLine, orders));
        }
    }

    class Orders
    {
        public Orders(string name,decimal price,int quantity)
        {
            Name = name;
            Price = price;
            Quantity = quantity;

        }
        public string Name { get; set; }
        public decimal Price { get; set; }
        public int Quantity { get; set; }

        public override string ToString()
        {
            decimal finalPrice = Price * Quantity;
            return $"{Name} -> {finalPrice}";
        }
    }
}

谢谢!

标签: c#

解决方案


    static void Main(string[] args)
    {
        List<Orders> orders = new List<Orders>();

        while (true)
        {
            string input = Console.ReadLine();
            if (input == "Buy") break;
            string[] tokens = input.Split();
            string product = tokens[0];
            decimal price = decimal.Parse(tokens[1]);
            int quantity = int.Parse(tokens[2]);
            Orders order = orders.Find(a => a.Name == product);
            if (order == null)
            {
                order = new Orders(product, price, quantity);
                orders.Add(order);
            }
            else
            {
                order.Price = price;
                order.Quantity += quantity;
            }
        }

        foreach (var order in orders)
        {
            Console.WriteLine($"{order.Name} :-> {(order.Price * order.Quantity)}");
        }
    }
}

推荐阅读