[英]Select objects from a collection with same property values
Is there an easy way to select the members with same currencyId's so I can sum them with each other, or do I need to do else if for every currencyId there is?有没有一种简单的方法可以将具有相同 currencyId 的成员加到 select,这样我就可以将它们相互求和,或者如果每个 currencyId 都存在,我还需要做其他事情吗?
if(model.CurrencyId == -1)
{
resultModel.Add(new ReportModel
{
AccountName = "Sum",
BalanceSum = resultModel.Where(q => q.CurrencyId == 1).Sum(q => q.Balance)
});
}
else
{
resultModel.Add(new ReportModel
{
AccountName = "Sum",
BalanceSum = resultModel.Sum(q => q.Balance)
});
}
To get the sum of the balance for each currency, you can preform groupBy
, followed by select
& sum
.要获得每种货币的余额总和,您可以
groupBy
,然后是select
& sum
。
Eg:例如:
var balanceSum = t.GroupBy(q => q.CurrencyId)
.Select(q => q.Sum(x => x.Balance));
To add it to the resultModel, you can do something like:要将其添加到 resultModel,您可以执行以下操作:
var reportData = t.GroupBy(q => q.CurrencyId)
.Select(q => new ReportModel()
{
AccountName = "Sum",
BalanceSum = q.Sum(x => x.Balance)
});
resultModel.AddRange(reportData);
If the data is only assigned to resultModel once, then you can probably replace AddRange with equals.如果数据只分配给 resultModel 一次,那么您可以将 AddRange 替换为 equals。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.