2017-08-07 131 views
1

我作爲LINQ獲得來自多個記錄的最新記錄列出

StudentName /教室/ GradeA/GradeB /格拉代茨/ GradeDate

學生教室是固定的,這樣列永遠不會改變的表。

每個學生都有不同的GradeDate的多個GradeA,GradeB和GradeC值。

public virtual IList<ClassroomDetail> GetLatestClassroomDetail(string classroom) 
    { 

     var query = from pc in _classroomDetailRepository.Table 
        where pc.Classroom == classroom 
        select pc; 

     var result = new List<ClassroomDetail>(query); 

     return result; 
    } 

上面的查詢返回一切,列表中有多個同樣的學生。

我怎樣才能得到最新的價值?

表:

ClassroomMaster

  • 編號
  • UpdateDate
  • 課堂

ClassroomDetail

  • 編號
  • CM_ID(與ClassroomMaster標識外鍵)
  • StudentName
  • GradeA
  • GradeB
  • 格拉代茨
  • GradeDate

在控制器

var bdetail = _classroomService.GetLatestClassroomDetail(classroom).OrderBy(d => d.StudentName); 

      var model = new List<ClassroomDetail>(); 
      foreach (var pr in bdetail) 
      { 

       model.Add(new ClassroomDetail 
       { 
        Id = pr.Id, 
        Classroom = pr.Classroom, 
        StudentName = pr.StudentName, 
        GradeA = pr.GradeA, 
        GradeB = pr.GradeB, 
        GradeC = pr.GradeC, 
        GradeDate = pr.GradeDate, 
       }); 
      } 


      return PartialView(model); 
+0

最新值分組?你能解釋更多嗎? – CodeNotFound

+0

是的,每個學生將會有一個記錄,並且只有最新的一個記錄 –

+0

,並且在我的控制器上我稱之爲var bdetail = _bunkerPriceService.GetLatestClassroomDetail(教室).OrderBy(d => d.StudentName); var model = new List (); foreach(var pr in bdetail) { –

回答

1

這將解決你的問題由學生

 var query = _classroomDetailRepository.Table 
     .Where(a => a.Classroom == classroom)    
     .Select(b => b.OrderByDescending(y => y.GradeDate).Take(1).FirstOrDefault()); 
1

我終於找到了解決辦法:d

public virtual IList<ClassroomDetail> GetLatestClassroomDetail(string classroom) 
    { 
     var query = _classroomDetailRepository.Table 
      .Where(z => z.Classroom == classroom) 
      .GroupBy(x => x.StudentName)     
      .Select(x => x.OrderByDescending(y => y.GradeDate).Take(1).FirstOrDefault()); 

     var result = new List<BunkerPriceDetail>(query); 

     return result; 
    } 
+1

大概正確,但冗餘'。取(1)',因爲'FirstOrDefault()'只返回最多一條記錄。 – tinudu

+1

爲什麼我的編輯恢復了?我錯了嗎?如果是的話,我想知道爲什麼。 – tinudu

+0

@tinudu ohhh,我猜我不小心做到了。對不起,這兩個作品。謝謝! –