2017-06-05 62 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; } 
}