C#将项目添加到列表

时间:2020-03-13 18:29:33

标签: c# list

我正在尝试将商品添加到下面的商品中,但是出现以下错误;

无法将项目隐式转换为System.Collection.Generic.List

我的商品类型如下;

public class Item
{
    [JsonProperty("variantId")]
    public int variantId { get; set; }

    [JsonProperty("quantity")]
    public int quantity { get; set; }

    [JsonProperty("returnReason")]
    public ReturnReason returnReason { get; set; } = new ReturnReason();
}

public class RootObject
{
    [JsonProperty("dropOff")]
    public DropOff dropOff { get; set; } = new DropOff();

    [JsonProperty("providerId")]
    public int providerId { get; set; }

    [JsonProperty("Reference")]
    public string Reference { get; set; }

    [JsonProperty("Id")]
    public int Id { get; set; }

    [JsonProperty("items")]
    public List<Item> items { get; set; } = new List<Item>();
}

我知道它们是两种不同的类型,但是我将如何克服这一点

这引发了错误;

items = (new Item
{ 
    quantity = csv.GetField<int>(""), 
    variantId = csv.GetField<int>(""), 
    returnReason = new ReturnReason
    { 
        code= csv.GetField<int>("") 
    } 
})

只需添加更多上下文,这就是我所说的方式

while (csv.Read())
{
    var booking = new ReturnsBooking.RootObject
    {
        dropOff = new DropOff {dropOffPointId = csv.GetField<string>("DropOffPointId") },
        providerId = csv.GetField<int>("ProviderID"),
        orderReference = csv.GetField("OrderReference"),
        returnMethodId = csv.GetField<int>("returnMethodId"),
        items = new Item
        {
            quantity = csv.GetField<int>(""), 
            variantId = csv.GetField<int>(""), 
            returnReason = new ReturnReason
            { 
                code = csv.GetField<int>("")
            }
        })
    };

    recordss.Add(booking);
}

return recordss;

当我尝试items.add时出现错误,指出项目不存在。我也曾尝试初始化Item ..这似乎也不起作用

1 个答案:

答案 0 :(得分:4)

由于未将项目添加到列表中,而是将项目分配到需要列表的变量而引发错误。这就是为什么您收到的异常提示您无法将项目转换为列表的原因。

您可以在RootObject的初始化中使用列表初始化:

var booking = new ReturnsBooking.RootObject
{
    items = new List<Item>
    {
        new Item
        { 
            quantity = csv.GetField<int>(""), 
            variantId = csv.GetField<int>(""), 
            returnReason = new ReturnReason
            { 
                code= csv.GetField<int>("") 
            } 
        }
    },
  //Other properties of RootObject...
}

或者您也可以像这样初始化RootObject之后添加项目:

var booking = new ReturnsBooking.RootObject {/* Initialize RootObject without adding the item ... */};

booking.items.Add(new Item
{ 
    quantity = csv.GetField<int>(""), 
    variantId = csv.GetField<int>(""), 
    returnReason = new ReturnReason
    { 
        code= csv.GetField<int>("") 
    } 
});