【问题标题】:how to calculate a key inside an array in c#如何在c#中计算数组中的键
【发布时间】:2020-11-25 05:01:31
【问题描述】:

我想在 C# 中计算一个数组中的一个键,但我不知道如何

这是我的 json

{ "id": "1312312312", "customer_name": "Tatang Sutarman", "table_number": "12", "Cart": [ { "product_name": "Mineral Water", "amount": 3, "price": 1000, "subtotal": 3000 }, { "product_name": "Coca Cola", "amount": 5, "price": 2000, "subtotal": 10000 } ], "total_price": 0 }

这是我的对象类

public class OrderRRModel 
{
    public ObjectId id { get; set; }
    public string customer_name { get; set; }
    public string table_number { get; set; }

    public IList<ListCart> Cart { get; set; }

    public OrderRRModel()
    {
        Cart = new List<ListCart>();
    }

    public double total_price { get; set; }
}

public class ListCart 
{
    public string product_name { get; set; }
    public int amount { get; set; }
    public double price { get; set; }
    public double subtotal { get; set; }

    public double GetTotal()
    {
        var subtotal = amount * price;
        return subtotal;
    }

}

我想计算数组内的小计,结果我将放入total_price

你能告诉我怎么做吗???

【问题讨论】:

  • total_price = Cart.Sum(x =&gt; x.subtotal) ?
  • 我想知道为什么您的数据中同时包含 amountprice 以及 subtotal。这是多余的。

标签: c# arrays json


【解决方案1】:

在你的模型中改变这个

public double total_price 
{ 
    set 
    {
        total_price = Cart.Sum(x => x.GetTotal());
    } 
    get;     
}

【讨论】:

  • 你的意思可能是get {return Cart.Sum(x =&gt; x.GetTotal());} ,或者?
  • 谢谢我得到了total_price,但我如何得到小计???它仍然是 0
  • 同样你可以在 CartList 模型中设置 {subtotal = amount * price;} 并使用 Cart.Sum(x => x.subtotal);在 OrderRRModel 模型中
  • get 怎么样?公共双小计{得到;设置{小计=金额*价格;它显示错误“get 必须声明一个主体,因为它没有标记为抽象或外部”
  • public double subtotal { get { return amount * price; } }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-09-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-22
  • 1970-01-01
  • 1970-01-01
  • 2018-11-01
相关资源
最近更新 更多