LINQ - 左连接和Group by和Sum

时间:2013-12-20 10:43:16

标签: c# linq linq-to-sql

我有两个列表

var stores = new[] 
{
    new { Code = 1, Name = "Store 1" },
    new { Code = 2, Name = "Store 2" }    
};

var orders = new[] 
{
    new { Code = 1, StoreCode = 1, TotalValue = 14.12 },
    new { Code = 2, StoreCode = 1, TotalValue = 24.12 }
};

输出

StoreName =商店1 | TotalValue = 38.24

StoreName =商店2 | TotalValue = 0

如何将其转换为LINQ to SQL?

var lj = (from s in stores
          join o in orders on s.Code equals o.StoreCode into joined
          from j in joined.DefaultIfEmpty()
          group s by new
          {
              StoreCode = s.Code,
              StoreName = s.Name
          }
              into grp
              select new
              {
                  StoreName = grp.Key.StoreName,
                  TotalValue = ???
              }).ToList();

1 个答案:

答案 0 :(得分:1)

当您进行群组加入时,与商店相关的所有订单都将在群组中,您将可以访问商店对象。因此,只需使用s.Name获取商店名称,然后使用g.Sum()计算订单总数:

var lj = (from s in db.stores
          join o in db.orders on s.Code equals o.StoreCode into g
          select new {
             StoreCode = s.Name,
             TotalValue = g.Sum(x => x.TotalValue)
          }).ToList();

注意 - 从您的示例中看起来您不需要按商店名称和代码进行分组,因为代码看起来像主键,并且您不太可能拥有多个具有相同主键但名称不同的商店。