如何更改对象类列表中的对象?

时间:2020-03-07 18:47:53

标签: c#

您就是力量,可以帮助我理解对象和类。

我有所有订单的清单(名称,价格和数量)。所以现在我应该检查清单中是否有两个或两个以上的时间,我应该添加数量并更新最后收到的价格 示例:啤酒2.40 350水1.25 200冰茶5.20 100啤酒1.20 200冰茶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}";
        }
    }
}

谢谢!

1 个答案:

答案 0 :(得分:0)

    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)}");
        }
    }
}