本文介绍了Linq Sum与group by的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有列的表结构
I am having a table structure with columns
收费普通
FeesCustom
FeesCustom
货币
现在我正在按货币查找SUM函数组.
Now i am looking for a SUM function group by currency .
例如,此表中的价格为20 USD + 30 EURO + 40 INR
For example 20 USD + 30 EURO + 40 INR something like this from this table
如果FeesCustom> 0,我还必须考虑这种情况,我必须忽略该行的FeesNormal
I also have to consider the scenario if FeesCustom > 0 I have to ignore FeesNormal for the row
采样日期和预期结果是这样
Sample date and expected result is like this
FeesNormal FeesCustom Currency
10 0 USD
15 25 USD //in this case can ignore FeesNormal Since FeesCustom is more
5 10 EUR //same for this row ignore FeesNormal
10 0 EUR
Expected result 35 USD 20 EUR
我可以使用linq找到总和
I able to find sum using the linq
int sum_custom=(int)fee_list.Where(p => p.FeesCustom > 0).Sum(p => p.FeesCustom);
int sum_normal = (int)fee_list.Where(p => p.FeesCustom ==0).Sum(p => p.FeesNormal);
推荐答案
在我看来,您只需要一个从入账"到有效费用"的投影,您可以将其相加-类似于:
It seems to me that you just need a projection from "entry" to "effective fee" which you can sum - something like:
var result = source
.GroupBy(x => x.Currency)
.Select(g => new {
Currency = g.Key,
Total = g.Sum(x => x.FeesCustom > 0 ? x.FeesCustom : x.FeesNormal)
});
等同于:
var result = source
.GroupBy(x => x.Currency,
(key, values) => new {
Currency = key,
Total = values.Sum(x => x.FeesCustom > 0 ? x.FeesCustom : x.FeesNormal)
});
或者更早进行转换:
var result = source
.Select(x => new {
x.Currency,
x.Fee = x => x.FeesCustom > 0 ? x.FeesCustom : x.FeesNormal
})
.GroupBy(x => x.Currency, x => x.Fee,
(key, values) => new { Currency = key, Fee = values.Sum() });
这篇关于Linq Sum与group by的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!