2009-12-18 70 views
1

我有這段代碼。如何使用SingleOrDefault方法檢查空值?如何檢查使用LINQ的空值

public static List<ETY.Rol> GetRolesByApplicationAndCompany(this UsuarioContext usuario, int company, int app) 
     { 
      List<ETY.Company> lCompanies= usuario.Companies; 

      var roles = lCompanies. 
       SingleOrDefault(e => (e.Id == company)).Applications. 
       SingleOrDefault(a => a.Id == app).Roles; 
      return roles; 

     } 

回答

0

你的意思返回null或一個空列表,如果任何SingleOrDefault回報的空?在這種情況下:

var company = lCompanies.SingleOrDefault(e => (e.Id == company)); 
if(company != null) { 
    var application = company.Applications.SingleOrDefault(a => a.Id == app); 
    if(application!=null) { 
     return application.Roles; 
    } 
} 
return null; //Or: return new List<ETY.Rol>(); 
1

你可以嘗試尋找一個可能/ IfNotNull擴展方法(herehere)。

或者使用Linq的語法像這樣(未經):

var q = from company in lCompanies.SingleOrDefault(e => e.Id == company) 
     where company != null 
     let application = company.Applications.SingleOrDefault(a => a.Id == app) 
     where application != null 
     select application.Roles; 

Greg Beech's answer是更好,如果單條件有保證)

+0

我很肯定你的第一行不會編譯,因爲它會返回一個不是IEnumerable的公司,這個公司不是。 – 2009-12-18 09:07:23

0

而不是使用SingleOrDefault可以按如下方式編寫鏈接查詢。你失去了確保只有一個應用程序或公司的語義,但是如果你知道總是這樣,那麼它不應該是一個問題。

return from c in lCompanies where c.Id == company 
     from a in c.Applications where a.Id == app 
     select a.Roles;