2017-04-01 106 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