2009-06-23 139 views
20

我試圖在「select new」中產生一個IF條件語句來檢查兩個字段的值以填充屬性。LINQ SELECT中的IF語句

from e in Employees 
where e.EmployeeID == id 
select new { 
    EmployeeID = e.EmployeeID, 
    EmployeeName = e.FirstName + " " + e.LastName, 
    Status = (if e.col1.HasValue then "This Value" else if e.col2.HasValue then "Other Value") 
} 

這些列是可以爲空的,因此列類型是DateTime?數據類型。

只有一列或其他列有日期時間值,而不是兩者。

我該如何去做這個?

回答

45
Status = e.col1.HasValue ? "This Value" : (e.col2.HasValue ? "Other Value" : null) 
+0

完美。謝謝。 – kntcnrg 2009-06-23 02:16:32

+0

你美麗的男人,當我返回Contact.Companies時,我在Windows Phone上得到一個NullReferenceException ...試圖獲得Contact.Companies.FirstOrDefault()。在LINQ查詢中的CompanyName被轟炸出來......下面的工作很棒! CompanyName =(c.Companies.Count()> 0)? c.Companies.FirstOrDefault()。公司名稱:「」 – 2012-11-26 21:35:43

3

使用空coelacing運營商這個

Status = e.col1.HasValue ? e.col1.Value ?? "This Value" : e.col2.Value ?? "Other Value"