使用GroupBy并根据条件显示不同的求和-LINQ Lambda表达式

时间:2018-11-27 01:02:11

标签: linq lambda group-by sum

我有一个3列的表格。

enter image description here

我想提供一个具有这种结构的表:

enter image description here

有人可以教我如何使用Lambda表达式吗?

到目前为止,只有在只显示一列的情况下,我才得到结果:

var sum_data = _context.HechosFinanza
                .Where(x => x.Product.Sale_Type == "Cash Sale")
                .GroupBy(x => x.Product.Product_Name)
                .Select(x => Product { Tienda = x.Key, Total = x.Sum(s => 
s.sales_amount) });

我不知道这样的事情是否有可能(真的不知道,只是想弄清楚)

var sum_data = _context.HechosFinanza
                // I remove there where condition from here
                .GroupBy(x => x.Product.Product_Name)
                // And I add the where condition in each sum
                .Select(x => Product { Tienda = x.Key, 
                         TotalCash = x.Sum(s => s.sales_amount).Where(s => s.Product.Sale_Type == "Cash Sale"),
                         TotalCredit = x.Sum(s => s.sales_amount).Where(s.Product.Sale_Type == "Credit Sale") 
                });

1 个答案:

答案 0 :(得分:1)

嗯,嗯。原来我真的很近。

只需要在前面加上“ Where”语句即可。

答案:

var sum_data = _context.HechosFinanza
                // I remove there where condition from here
                .GroupBy(x => x.Product.Product_Name)
                // And I add the where condition in each sum
                .Select(x => Product { Tienda = x.Key, 
                         TotalCash = x.Where(s => s.Product.Sale_Type == "Cash Sale").Sum(s => s.sales_amount),
                         TotalCredit = x.Where(s.Product.Sale_Type == "Credit Sale") .Sum(s => s.sales_amount)
            });

完成。