2016-11-12 72 views
1

我有3個表連接主要和外國的概念。Linq Select最大值數據集

模型 - > studentRecord

public class studentRecord 
{ 
    public string studentName{ get; set; } 
    public int year{ get; set; } 
} 

表1 - >學生

studentId studentName 
---------------------- 
1    Sam 
2    Mani 
3    rajah 

表2 - >受試者

subjectid subjectName 
------------------------ 
    1   english 
    2    maths 
    3   physics 

表3 - >寄存器

registerId studentId subjectid Year 
-------------------------------------------- 
    1   1    1  1 
    2   1    2  1 
    3   1    3  1 
    4   1    1  2 
    5   1    2  2 
    6   1    3  2  

我想獲得學生第二年的記錄。
我的LINQ代碼

var op = (from student in db.student.where(x => x.studentId == 1) 
      join register in db.register 
      on student.studentId equals register.studentId 
      select new studentRecord{studentName = student.studentName, year = register.Year}).ToList<studentRecord>().Max(x => x.Year) 

我得到的錯誤。有沒有任何表現良好的應用程序。在此先感謝

+4

後的錯誤消息也是如此。幫助找到確切的原因。 –

+0

like max不能應用 – anand

+0

在調用Max之前,將LINQ結果轉換爲List,然後調用Max()(即(...).ToList().Max()。) –

回答

1

已經在Linqpad測試了查詢,下面的查詢對我來說工作得很好。

void Main() 
{ 
    var op = (from student in Students.Where(x => x.StudentId == 1) 
       join register in Registers 
       on student.StudentId equals register.StudentId 
       select new {student = student.StudentName, Year = register.Year}) 
    .Max(x => x.Year); 

    op.Dump(); 
} 

並且事件探查器顯示以下SQL。

exec sp_executesql N'SELECT MAX([t1].[Year]) AS [value] 
FROM [student] AS [t0] 
INNER JOIN [register] AS [t1] ON [t0].[studentId] = [t1].[studentId] 
WHERE [t0].[studentId] = @p0',N'@p0 int',@p0=1 

反正你可能想要的東西是這樣的:

from student in Students.Where(s => s.StudentId == 1) 
join register in Registers.Where(r => r.Year == Registers.Max(x => x.Year)) 
on student.StudentId equals register.StudentId 
select new studentRecord 
    { 
     studentName = student.StudentName, 
     year = register.Year 
    }) 
.ToList<studentRecord>(); 

Students是在你的代碼db.student