LINQ - 与Group by进行多连接并获得平均值

时间:2013-05-03 02:05:33

标签: c# linq join average

我正在尝试在LINQ中编写此选择但是我很长时间没有成功修复它。我也试过LINQ - join with Group By and get average,但它在我的代码中不起作用。显然我错了。

SQL:

SELECT name_type, AVG(t.price) as avgPrice FROM type tp
JOIN location l ON l.ID_type = tp.ID 
JOIN event e ON e.ID_location = l.ID
JOIN ticket t ON t.ID_event = e.ID
GROUP BY tp.name_type

LINQ:

var q3 = from l in db.location
join tp in db.type on l.ID_type equals tp.ID
join e in db.event on l.ID equals u.ID_location
join t in db.ticket on e.ID equals t.ID_event 
group tp by new {Type_name = tp.type_name} into grp
select new
{
     Type_name = grp.Key.type_name,
     avgPrice = grp.Average( x => x.ticket.price)
};

1 个答案:

答案 0 :(得分:3)

有一些问题:

  1. 第二次加入时出错 - 我认为u.ID_location需要e.ID_location
  2. 我认为您正在对错误的实体进行分组,请尝试按t而不是tp进行分组。
  3. 您不需要group by中的匿名类型。
  4. 试试这个:

    var results = 
         from l in db.location
         join tp in db.type on l.ID_type equals tp.ID
         join e in db.event on l.ID equals e.ID_location
         join t in db.ticket on e.ID equals t.ID_event 
         group t by new tp.type_name into grp
         select new
         {
              Type_name = grp.Key,
              avgPrice = grp.Average(x => x.price)
         };
    

    如果您碰巧在实体之间设置了导航属性,这将更加容易。很难说实体假设是如何相关的,但我认为这样的事情会起作用:

    // average ticket price per location type
    var results = 
        from t in db.ticket
        group t by t.event.location.type.type_name into g
        select new
        {
             Type_name = g.Key,
             avgPrice = g.Average(x => x.price)
        }; 
    

    或者用流利的语法:

    var results = db.ticket.GroupBy(t => t.event.location.type.type_name)
                           .Select(g => new 
                                   { 
                                       Type_name = g.Key, 
                                       avgPrice = g.Average(x => x.price) 
                                   });