2017-04-01 154 views
0

我已经在linq中使用左连接和使用group by和order by编写了此查询。我有2张桌子,学生和课程。所以我没有收到任何栏目,所以我在学生桌上进行分组,所以我怎样才能在课程表中在日期时间栏中进行排序。Linq使用如何使用order by和group by with left join?

tablestudent:

ID,名称,标准

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. 

如果有谁知道怎么样要做到这一点,请帮助。

+0

你能告诉学生,当然实体和要选择 – jitender

+0

好吧,我编辑我的问题,并显示我的实体哪些列。 – coderwill

+0

我编辑我的question.and我想所有的实体像名称,std adn在课程表中的日期时间与秩序由 – coderwill

回答

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

+0

我已经试过这个波,但我在课程表中获取所有的数据,我不想所有的数据按顺序通过datetime刚刚得到letus第一个记录。 sry我很清楚地说这个问题 – coderwill

+0

意思是只想在课程表中使用datetime order by – coderwill

+0

首先或默认记录你能帮我一下吗?如何使用datetime和你的最新更新记录解。 – coderwill