加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – Linq Sum with group by

发布时间:2020-12-15 18:08:59 所属栏目:百科 来源:网络整理
导读:我有一个带有列的表结构 FeesNormal FeesCustom 货币 现在我正在寻找按货币计算的SUM功能组. 例如20美元30欧元40 INR来自此表 如果FeesCustom我还必须考虑这个场景. 0我必须忽略该行的FeesNormal 样本日期和预期结果是这样的 FeesNormal FeesCustom Currency
我有一个带有列的表结构

FeesNormal

FeesCustom

货币

现在我正在寻找按货币计算的SUM功能组.

例如20美元30欧元40 INR来自此表

如果FeesCustom>我还必须考虑这个场景. 0我必须忽略该行的FeesNormal

样本日期和预期结果是这样的

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找到总和

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);

解决方法

在我看来,你只需要从“入门”到“有效费用”的预测,你可以总结 – 如:
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,values) => new { Currency = key,Fee = values.Sum() });

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读