簡體   English   中英

將項目組添加到列表

[英]Add group of items to List

我正在嘗試從Web API獲取項目集合。

var sampleDataGroups = new List<SampleDataGroup>();

if (response.IsSuccessStatusCode)
{
    var content = await response.Content.ReadAsStringAsync();

    // CL: Parse 1 Product from the content
    var product = JsonConvert.DeserializeObject<dynamic>(content);

    foreach (var data in product)
    {
        var dataGroup = new SampleDataGroup
        (
            (string)product.Id.ToString(),
            (string)product.Name,
            (string)"",
            (string)product.PhotoUrl,
            (string)product.Description
        );
        sampleDataGroups.Add(dataGroup);
    }
}

我試圖將其用於每個添加返回到SampleDataGroup列表的每個產品信息。 這樣我就可以查看該列表中返回的所有產品的列表。

這是我要從網絡api返回的產品列表

public IEnumerable<Product> GetAllProducts()
{
    return products;
}

但是我收到異常錯誤。

如何將返回的每個產品寫入/添加到SampleDataGroups列表中?

您需要訪問data ,而不是product在你的循環體:

foreach (var data in product)
{
    var dataGroup = new SampleDataGroup(
        (string)data.Id.ToString(),
        (string)data.Name,
        (string)"",
        (string)data.PhotoUrl,
        (string)data.Description);

    sampleDataGroups.Add(dataGroup);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM