如何使用linq使用group by并对数据库记录求和

时间:2019-01-10 23:56:46

标签: c# linq

我有一个看起来像这样的表结构

 listed_companyid         numberof_units           userid
-----------------     -----------------        ----------------
       2                     4                        2
       2                     2                        2   
       1                     6                        2
       5                     3                        3

对于userid = 2我想要

total_unit = 12 

// Additionally

listed_companyid = 2, total = 6
listed_companyid = 1, total = 6

代码

var  listed = dbContext.listedCompanies.ToList();
var stock = dbContext.stocks.Where(m=>m.userid == 2).ToList();
var result = (from s in stock
              join l in listed on s.listed_companyid equals l.id group s  by new { s.listed_companyid } into g select new
              {
                  g.Key,
                  total_unit = g.Sum(s => s.numberof_units)
              });

1 个答案:

答案 0 :(得分:1)

您可以投影嵌套的GroupBy

给出

public class Something
{
     public int listed_companyid { get; set; }
     public int numberof_units { get; set; }
     public int userid { get; set; }
}

示例应用

var list = new List<Something>
           {
              new Something() { listed_companyid = 2, numberof_units = 4, userid = 2 },
              new Something() { listed_companyid = 2, numberof_units = 2, userid = 2 },
              new Something() { listed_companyid = 1, numberof_units = 6, userid = 2 },
              new Something() { listed_companyid = 5, numberof_units = 3, userid = 3 },   
           };

var results = list.GroupBy(x => x.userid)
                  .Select(x => new 
                               {
                                  userId = x.Key,
                                  total_unit = x.Sum(y => y.numberof_units),
                                  sub = x.GroupBy(y => y.listed_companyid)
                                         .Select(y => new
                                                      {
                                                         listed_companyid = y.Key,
                                                         total = y.Sum(z => z.numberof_units)
                                                      })
                               });

foreach (var result in results)
{
   Console.WriteLine("userId : " + result.userId + ", total_unit  : " + result.total_unit);

   foreach (var sub in result.sub)
       Console.WriteLine(" - listed_companyid : " + sub.listed_companyid + ", total : " + sub.total);
}

输出

userId : 2, total_unit : 12
 - listed_companyid : 2, total : 6
 - listed_companyid : 1, total : 6
userId : 3, total_unit  : 3
 - listed_companyid : 5, total : 3

Full Demo Here

注意:转换为查询语法,并根据需要转换为IQueryable