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

时间:2013-01-23 17:23:34

标签: c# linq

下面的代码为每个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”列上进行求和,还是需要进行新的查询?

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

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