public class APIBillingHistory
{
public List<APIBillingHistoryDetails> BillingHistoryDetails;
}
public class APIBillingHistoryDetails
{
public List<APIBillingHistoryPaymentType> PaymentType;
public string BillId;
}
public class APIBillingHistoryPaymentType
{
public string Description;
public Decimal Principal;
}
我有一类嵌套列表对象。我想将相应的 PaymentList
集合合并到其父列表 APIBillingHistoryDetails
例如:
APIBillingHistory
-----BillingHistoryDetails
Bill ID : 123
----PaymentType
Description : "A"
Principal : 100
----PaymentType
Description : "B"
Principal : 200
-----BillingHistoryDetails
Bill ID : 123
----PaymentType
Description : "A"
Principal : 150
----PaymentType
Description : "B"
Principal : 300
假设我在上面指定了样本日期。我希望得到以下格式的结果。在这里,我通过添加 Principal
属性来合并 PaymentList
每个 描述
值(如果它们具有相同的帐单 ID
输出应如下所示:
APIBillingHistory
-----BillingHistoryDetails
Bill ID : 123
----PaymentType
Description : "A"
Principal : 250
----PaymentType
Description : "B"
Principal : 500
最佳答案
这将给出所需的输出
var merged = new APIBillingHistory {
BillingHistoryDetails = history
.BillingHistoryDetails
.GroupBy(detail => detail.BillId) //Group same bill Ids
.Select(detailGroup => new APIBillingHistoryDetails {
BillId = detailGroup.Key,
PaymentType = detailGroup.SelectMany(p => p.PaymentType) //Get all payments
.GroupBy(pymtType => pymtType.Description) //and group them by description
.Select(pymtTypeGroup => new APIBillingHistoryPaymentType { //construct payment type
Description = pymtTypeGroup.Key,
Principal = pymtTypeGroup.Sum(t => t.Principal) // summing all grouped principals
}).ToList()
}).ToList()
};
给定
var history = new APIBillingHistory {
BillingHistoryDetails = new List<APIBillingHistoryDetails> {
new APIBillingHistoryDetails {
BillId = "123",
PaymentType = new List<APIBillingHistoryPaymentType>{
new APIBillingHistoryPaymentType {
Description = "A",
Principal = 100
},
new APIBillingHistoryPaymentType {
Description = "B",
Principal = 200
}
}
},
new APIBillingHistoryDetails {
BillId = "123",
PaymentType=new List<APIBillingHistoryPaymentType>{
new APIBillingHistoryPaymentType {
Description = "A",
Principal = 150
},
new APIBillingHistoryPaymentType {
Description = "B",
Principal = 300
}
}
}
}
};
关于c# - 在 C# 中使用 linq 合并列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44664195/