Linq使用如何使用order by和group by with left join?

时间:2017-04-01 06:50:16

标签: linq

我使用左连接并使用group by和order by在linq中编写了此查询。我有2张桌子,学生和课程。所以我在学习桌上分组后,我没有在课程中获得任何专栏,所以如何在datetime专栏的课程表上订购。

tablestudent:

id,name,std

tablecourse:

ID,用户ID,日期时间

这是我的疑问:

 var res = (from u in db.student
              join c in db.course on u.id equals c.userid into j1
              from j2 in j1.DefaultIfEmpty()                       
              group j2 by u.id into g
              orderby g.Key.datatime descending    // here i'm getting datetime does not contain.
              select new { id = g.key }).tolist(); // here i just want id not getting any other column.

如果有人知道该怎么做,请帮助。

1 个答案:

答案 0 :(得分:1)

这个怎么样

   var query =db.course.GroupBy(c => c.UserId)
             .Select(g => g.OrderByDescending(c => c.datetime).FirstOrDefault());
        var res = (from u in db.student
              join c in query on u.id equals c.userid into j1
              from j2 in j1.DefaultIfEmpty()     
              select new {   u.name,j2}).ToList();

Working fiddle