2011-05-10 66 views
3

假設查詢中有5條記錄,我如何獲得前1條記錄?這是我現在的代碼。如何從查詢中獲得前1條記錄

public Application GetByUserIdAndVersion(int userId, string version) 
{ 
    VettingDataContext dc = new VettingDataContext(_connString); 
    return (from a in dc.Applications 
      where a.UserId == userId && a.chr_Version == version 
      select a).SingleOrDefault<Application>(); 
} 

回答

7

只需使用FirstOrDefault()代替:如果有一個以上的記錄,FirstOrDefault()將只取前一個

return (from a in dc.Applications 
     where a.UserId == userId && a.chr_Version == version 
     select a).FirstOrDefault<Application>(); 

SingleOrDefault()會拋出異常。您的記錄已經是Application類型。

1

的第一條記錄,你可以嘗試:

return (from a in dc.Applications where a.UserId == userId && a.chr_Version == version select a).FirstOrDefault(); 

最初的N個用途:

return (from a in dc.Applications where a.UserId == userId && a.chr_Version == version select a).Take(N); 
相關問題