如何将列表数据添加到多子类列表数据?

时间:2018-10-01 15:57:50

标签: c# list linq class subclass

我想将列表数据从子类(列表)添加到子类(列表)以发送JSON格式。

课程

public class MainProcess
{ 
  public Pay _pay { get; set; }
}

public class Pay
{
   public Credit _credit { get; set; }
}

public class Credit 
{
  public int payid { get; set; }
  public List<CreditDetails> details { get; set; }
}

public class CreditDetails
{
  public decimal total { get; set; }
  public List<CreditSubDetails> details { get; set; }
}

public class CreditSubDetails //i want add data to here.
{
  public string runid { get; set; }
  public decimal amount { get; set; }
}

代码C#

private async Task<.....> CreateInfo(Information r)
{
    .....
    ..... //Process Data
    .....

    //Add Data                 
    List<CreditSubDetails> detailsCredit = new List<CreditSubDetails>();
    foreach (var res in resPayDetail.Data.ToList()) //Set data to list
    {
       detailsCredit.Add(new CreditSubDetails()
        {
           runid = res.runid,
           amount = res.totalamount
        });
    }

    var subCreditCardDetails = r._pay._credit.details.SelectMany(x => x.details).ToList();

    //i want add list data to sub class list (class CreditSubDetails)
    //r._pay._credit.details.details = detailsCredit *but not work.

    .....
    .....
    //sent all data (format json)
    response = await client.PostAsJsonAsync("", r._pay._credit);
    .....
    .....
}

请帮帮我。预先感谢。

1 个答案:

答案 0 :(得分:0)

I assume you want to add the list detailsCredit data to the your Information r structure in the path r._pay._credit.details.details the only issue as I can see is that you can't access a property of an item through the list of the same item type directly ...

you can't access details property of CreditDetails class from List<CreditDetails> ... you'll need to loop over each item and set details for each one.

it should be something like this:

r._pay._credit.details.ToList().ForEach(d => {
    d.details = detailsCredit;
});