Linq 返回同一查询中 2 个单独列的总和

本文关键字:单独列 返回 查询 Linq | 更新日期: 2023-09-27 17:55:20

下面的代码为每个InvNo带来了一行,以及"SCharge":0的总和

var Values = from data in DtSet.Tables["tblCosts"].AsEnumerable()
            group data by new
            {
                InvNo = data.Field<double>("InvoiceNo"),
                AccRef = data.Field<double>("SiteRefNum"),
            }
            into g
            select new
            {
                Code = "1",
                InvType = "I",
                Account = g.Key.AccRef,
                InvNo = g.Key.InvNo,
                SCharge = g.Sum(d => d.Field<double>("SCharge"))
            };

有没有办法修改它,以便我在下面得到另一组行,这次对"TCharge"列做一个总和,还是我需要做一个新的查询?

Linq 返回同一查询中 2 个单独列的总和

因此,由于您希望显示所有行两次,但第二次的投影略有不同,因此我们可以首先保存分组的查询,然后对这些组执行两个投影并将它们组合在一起。

var groupings = DtSet.Tables["tblCosts"].AsEnumerable()
                .GroupBy(data => new
                {
                    InvNo = data.Field<double>("InvoiceNo"),
                    AccRef = data.Field<double>("SiteRefNum"),
                }).ToList();
var Values = groupings.Select(g => new
{
    Code = "1",
    InvType = "I",
    Account = g.Key.AccRef,
    InvNo = g.Key.InvNo,
    Charge = g.Sum(d => d.Field<double>("SCharge"))
})
.Concat(groupings.Select(g => new
{
    Code = "1",
    InvType = "I",
    Account = g.Key.AccRef,
    InvNo = g.Key.InvNo,
    Charge = g.Sum(d => d.Field<double>("SCharge"))
}));
select new
     {
       Code = "1",
        InvType = "I",
        Account = g.Key.AccRef,
        InvNo = g.Key.InvNo,
        SCharge = g.Sum(d => d.Field<double>("SCharge")),
        TCharge = g.Sum(d => d.Field<double>("TCharge"))
     };