c# - 如何更改对象类列表中的对象?
问题描述
你是可以帮助我理解对象和类的力量。
我有所有订单的清单(名称、价格和数量)。所以现在我应该检查某个项目是否在列表中出现两次或更多时间,我应该添加数量并更新最后收到的价格示例:啤酒 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}";
}
}
}
谢谢!
解决方案
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)}");
}
}
}
推荐阅读
- powershell - 将 Set-PnPListItem 与“发布图像”类型一起使用
- android - FileNotFoundException SQLite 数据库 Android
- swiftui - 文本视图的 lineBreakMode 是否有 SwiftUI 等效项?
- javascript - 使用多个参数过滤 JSON 对象
- android - 如何在android中设计一个动态cardView,使两个cardView彼此相邻?
- javascript - 来自基于 Sencha 的 api 的未知 json 响应
- css - 在 flex 中断时更改文本对齐方式
- anylogic - 如何在 Anylogic 中以编程方式排除(忽略)GIS 路线?
- python - 如何匹配组中最接近的文本?
- java - testcontainers - 由于测试失败,Maven 构建失败