2017-06-05 18 views
0

我寫了一個查詢從tbl中選擇最高記錄。我要檢查,如果沒有記錄在TBL我的查詢返回像(StudentId = 1,高分= 0)假數據
IF NOT EXIST Recored選擇一些數據

var queryWin = (from T in ((from tbl_ActPoints in dc.tbl_ActPoints 
       select new 
       { 
        tbl_ActPoints.StudentId, 
        tbl_ActPoints.Score 
       })) 
    group T by new 
    { 
     T.StudentId 
    } into g 
    orderby 
     ((System.Int32?)g.Sum(p => p.Score) ?? (System.Int32?)0) descending 
    select new 
    { 
     g.Key.StudentId, 
     HighScore = ((System.Int32?)g.Sum(p => p.Score) ?? (System.Int32?)0) 
    }).Take(1); 

回答

0

試試這個:

var queryWin = (from T in ((from tbl_ActPoints in dc.tbl_ActPoints 
       select new 
       { 
        tbl_ActPoints.StudentId, 
        tbl_ActPoints.Score 
       })) 
    group T by new 
    { 
     T.StudentId 
    } into g 
    orderby 
     ((System.Int32?)g.Sum(p => p.Score) ?? (System.Int32?)0) descending 
    select new 
    { 
     g.Key.StudentId, 
     HighScore = ((System.Int32?)g.Sum(p => p.Score) ?? (System.Int32?)0) 
    }).Take(1); 

var result = queryWin.FirstOrDefault(); 

if (result == null) 
    result = new { StudentId = 1, HighScore=0 }; 
+0

它不工作,我必須在哪裏使用此代碼? –

+0

編輯了答案 – coolswastik

0

清理代碼位:

var queryWin = (from tbl_ActPoints in dc.tbl_ActPoints 
       group new 
       { 
        tbl_ActPoints.StudentId, 
        tbl_ActPoints.Score 
       } by tbl_ActPoints.StudentId into g 
       orderby 
        (g.Sum(p => p.Score) ?? 0) descending 
       select new StudentHighScore 
       { 
        g.Key.StudentId, 
        HighScore = (g.Sum(p => p.Score) ?? 0) 
       }).FirstOrDefault() 
        ?? new StudentHighScore { StudentID = 1, HighScore = 0}; 

訣竅,原因coolswastik的代碼沒有工作,因爲這兩個匿名對象,即使有相同的屬性,總是不同的,所以你需要一個名爲類:

class StudentHighScore 
{ 
    public int StudentId { get; set; } 
    public int HighScore { get; set; } 
}