LINQ中多个单独列上的SUM

时间:2014-07-28 11:09:09

标签: c# sql linq sum

有谁知道如何正确有效地汇总多个列。

我有一个大规模的加入查询

db.myTable.Join(...)
.Join(...)
.Join(...)
.Join(...)
.Join(...)
.Join(...)
.Where(...)

我现在需要做的是总和A,B,C和D列。并计算E。

所以我有一张记录中的总和。

我尝试过使用分组依据和Select(x => new myClass{A => x.})

以下 MAJORLY 效率低下

myClass mine = new myClass{ 
            Number = myList.GroupBy(x => x.u.ID).Count(),
            Area = myList.Sum(a => a.u.Area ?? 0),
            Rent = myList.Sum(a => a.r.Rent ?? 0)   ,
            ERV = myList.Sum(a => a.e.ERV ?? 0)
        };

以下是Efficient,但只对第一个分组进行总结......

      myClass mine = (from p in myList
                            group p by p.u.ID into g
                            select  new myClass
                            { 
                                Number = g.Count(),
                            Area = g.Sum(a => a.u.Area ?? 0),
                            Rent = g.Sum(a => a.r.Rent ?? 0)   ,
                            ERV = g.Sum(a => a.e.ERV ?? 0)
        }).FirstOrDefault();

1 个答案:

答案 0 :(得分:1)

我认为您正在尝试在单个记录中使用其他字段的未分组 Distinct Count()来获取号码字段Sum()

var mine = (from x in (from p in mc 
                       group p by p.u.id into g1
                       select new { 
                             Number = g1.Count(),
                             Area = g1.Sum(a => a.u.Area??0),
                             Rent = g1.Sum(a => a.u.Rent??0),
                             ERV = g1.Sum(a => a.e.ERV ?? 0)
                       })
                    group x by 1 into g2
                    select new myClass {
                             Number = g2.Count(),
                             Area = g2.Sum(a => a.Area),
                             Rent = g2.Sum(a => a.Rent),
                             ERV = g2.Sum(a => a.ERV)
                    }).FirstOrDefault();