动态添加嵌套列表到对象

时间:2021-04-05 11:15:48

标签: c#

我需要向对象添加嵌套列表。我有这个带有物品清单的购物车。我正在尝试将该项目列表与其他属性一起作为字符串对象发送。我遍历我的列表

runtime: nodejs10

env_variables:
  VUE_APP_API_URL: "https://api.example.com"

handlers:
  - url: /(.*\..+)$
    static_files: dist/\1
    upload: dist/(.*\..+)$
  - url: /.*
    static_files: dist/index.html
    upload: dist/index.html

此方法确实会发送列表,但只会发送我购物车中的最后一项。 我的订单型号是

public string SendOrderEmailBody()
        {
            var connection = DependencyService.Get<ISQLite>().GetConnection();
            var orderData = connection.Table<ItemCartModel>().ToList();
            float totalCost = 0f;
            List<PlaceOrderModel> orderModel = new List<PlaceOrderModel>();
            for (int i = 0; i < orderData.Count; i++)
            {
                totalCost += (orderData[i].ItemPrice * orderData[i].ItemQuantity);
                orderModel = new List<PlaceOrderModel>
                {
                    new PlaceOrderModel()
                    {
                        PlacedOrderItemname = orderData[i].ItemName,
                        PlacedOrderQuantity = orderData[i].ItemQuantity,
                        PlacedOrderItemDough = orderData[i].ItemDough,
                        PlacedOrderItemSauce = orderData[i].ItemSauce,
                        PlacedOrderItemPrice = orderData[i].ItemPrice
                    }
                };
                TotalCost = totalCost;
            }
            Order OrderDetails = new Order
            {
                UserName = NameText,
                UserPhone = PhoneText,
                OrderItems = orderModel,
                TotalCost = totalCost
            };
            var content = JsonConvert.SerializeObject(OrderDetails);
            return content;
        }

我的解决方案只是遍历 for 循环,而不是将整个购物车项目添加到 orderModel。

1 个答案:

答案 0 :(得分:0)

为什么只有最后一项保留在您的列表中是因为行 orderModel = new List<PlaceOrderModel> 实例化了一个新的订单模型列表。

一个快速的解决方案是添加一个项目而不是重新实例化 orderModel

orderModel.Add(new PlaceOrderModel()
{
    PlacedOrderItemname = orderData[i].ItemName,
    PlacedOrderQuantity = orderData[i].ItemQuantity,
    PlacedOrderItemDough = orderData[i].ItemDough,
    PlacedOrderItemSauce = orderData[i].ItemSauce,
    PlacedOrderItemPrice = orderData[i].ItemPrice
});