我有像
这样的结构ID Description Principal Interest Total
123 Paid 100 150 250
Balance 50 50 100
Total ? ? ?
124 Paid 100 150 250
Balance 50 50 100
Total ? ? ?
班级:
public class APIBillingHistory
{
public List<APIBillingHistoryDetails> BillingHistoryDetails;
}
public class APIBillingHistoryDetails
{
public string BillId;
public string Description;
public Decimal Principal;
public Decimal Interest;
public Decimal Total;
}
我想为每个ID 的每列加总值。因此,在上面的示例中,Total
的ID 123的Principal
同样为150,Interest
200。我在这里检查了这个解决方案How to create Total column and Total row using LINQ但是无法得到它。
代码:
responseObj = new APIBillingHistory
{
BillingHistoryDetails = billingHistory.BillingHistoryDetails
.GroupBy(detail => new { detail.BillId, detail.Description})
.Select(group => new APIBillingHistoryDetails
{
BillId = group.Key.BillId,
Description = group.Key.Description,
Principal = group.Sum(t => t.Principal),
Interest = group.Sum(t => t.Interest),
Total = group.Sum(t => t.Principal) + group.Sum(t => t.Interest)
}).Concat(new APIBillingHistoryDetails
{
Description = "Total",
/* Not sure what to write over here */
})
};
编辑:
澄清我想要实现的目标:
Principal
&amp; Interest
将包含decimal
格式的值。ID
列是一个整数。我想显示每个ID
Principal
&amp;的值Interest
是基于ID
汇总计算的,在计算之后,只会显示Total
行。 任何建议?
答案 0 :(得分:1)
您无法使用Concat
并参考以前的数据。您需要使用SelectMany
:
BillingHistoryDetails = billingHistory.BillingHistoryDetails
.GroupBy(detail => detail.BillId)
.SelectMany(bg => bg.Concat(new[] { new APIBillingHistoryDetails {
BillId = bg.First().BillId,
Description = "Total",
Principal = bg.Sum(b => b.Principal),
Interest = bg.Sum(b => b.Interest),
Total = bg.Sum(b => b.Total)
} }));
答案 1 :(得分:0)
假设当前数据
BillId Description Principal Interest
123 Paid 100 150
123 Balance 50 50
124 Paid 100 150
124 Balance 50 50
然后只按身份分组,通过总结分组属性来创建总对象,将描述设置为&#34; Total&#34; 。
var totalsObj = new APIBillingHistory {
BillingHistoryDetails = billingHistory.BillingHistoryDetails
.GroupBy(detail => detail.BillId)
.Select(g => new APIBillingHistoryDetails {
BillId = g.Key,
Description = "Total",
Principal = g.Sum(detail => detail.Principal),
Interest = g.Sum(detail => detail.Interest),
Total = g.Sum(detail => detail.Principal) + g.Sum(detail => detail.Interest)
}).ToList()
};
和totalsObj.BillingHistoryDetails
可能需要输出
在计算之后,只显示总行数。
BillId Description Principal Interest Total
123 Total 150 200 350
124 Total 150 200 350