【问题标题】:LINQ - multi join with Group by and get averageLINQ - 与 Group by 多连接并获得平均值
【发布时间】:2013-05-03 02:05:33
【问题描述】:

我正在尝试在 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)
};

【问题讨论】:

    标签: c# linq join average


    【解决方案1】:

    有几个问题:

    1. 第二次连接有错误——我认为u.ID_location 必须是e.ID_location
    2. 我认为您分组的实体有误,请尝试按 t 而不是 tp 分组。
    3. group by 中不需要匿名类型。

    试试这个:

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

    【讨论】:

    • 非常感谢!它工作得很好:) 现在我可以去尝试更困难的选择......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-09
    • 2016-06-13
    • 1970-01-01
    • 2020-11-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多