如何使用Linq将列表数据添加到列表子类?

时间:2018-09-25 17:21:36

标签: c# list linq class subclass

我想将列表数据(来自类)添加到子类列表中,以将JSON FORMAT发送到其他api。

课程

public class InPaymentDetailResponse
{
       public List<InPaymentDetail> Data { get; set; }        
}

public class InPaymentDetail
{
       public string runningno { get; set; }
       public decimal totalpremium { get; set; }
}

public class InformationRequest
{        
    ..... 
    ..... 
    public List<CreateDetailRequest> _detailData { get; set; }
    public ExPaymentRequest _payment { get; set; }
}

public class ExPaymentRequest
{
   .....
   .....    
   public ExCashtransaction _cash { get; set; }

}

public class ExCashtransaction
{        
     public string createby { get; set; }
     public DateTime createdate { get; set; }
     public List<ExCashtransactionDetailsRequest> details { get; set; }
}

public class ExCashtransactionDetailsRequest
{
        public string runningno { get; set; }
        public decimal amount { get; set; }
}

代码C#

private async Task<.....> CreateInfo(InformationRequest r)
{

InPaymentDetailResponse resPaymentDetail = new InPaymentDetailResponse();
resPaymentDetail.Data = new List<InPaymentDetail>();

foreach (var item in r._detailData)
{
    .....
    ..... //Process Data
    .....

    var resPaymentDetailData = new InPaymentDetail
    {
        //Add List Data To New Object
        runningno = item.runningno,
        totalpremium = item.totalpremium
    };
    resPaymentDetail.Data.Add(resPaymentDetailData);
}

HttpResponseMessage response = new HttpResponseMessage();
foreach (var res in resPaymentDetail.Data.ToList())
{
     //i want add
     //req._payment._cash.details.runningno = res.runningno  //Ex. 10
     //req._payment._cash.details.amount = res.amount  //Ex. 99.9

     //next loop
     //req._payment._cash.details.runningno = res.runningno  //Ex. 20
     //req._payment._cash.details.amount = res.amount  //Ex. 23.2
}

//sent to other api
response = await client.PostAsJsonAsync("", req._payment._cash);

.....
.....

}

在将列表数据添加到re_.payment._cash中时,我想要结果代码: (因为可以在下一个流程中使用它)

"createby": "system",
  "createdate": 26/09/2018",
  "details": [
    {
      "runningno": "10", //before add data to list is null
      "amount": 99.9 //before add data to list is null
    },
     {
      "runningno": "20", //before add data to list is null
      "amount": 23.2 //before add data to list is null
     }
   ]

请帮帮我。提前致谢。

1 个答案:

答案 0 :(得分:0)

List<ExCashtransactionDetailsRequest> detailsObj = new List<ExCashtransactionDetailsRequest>();

foreach (var res in resPaymentDetail.Data.ToList())
{

detailsObj.Add(new  ExCashtransactionDetailsRequest(){ runningno  =res.runningno, amount = res.amount });
}

最后,将详细信息对象添加到您的媒体资源

req._payment._cash.details = detailsObj;