2013-07-18 55 views
0

即時尋找任何建議更好的方式來編寫以下在LINQ?更好的方式來編碼這個linq語句

var tblequipments = from d in db.tblEquipments.Include(t => t.User).Include(t => t.ChangeLog).AsEnumerable()       
    where ((d.Development != 1 || d.Development == null) && 
      (d.Deleted != 1 || d.Deleted== null) && 
      (d.Stock != 1 || d.Stock == null)) && 
      (d.DecommissionDate == Convert.ToDateTime("1900-01-01") || d.DecommissionDate == null) 
select d; 

感謝

+0

如果你在談論可讀性,那麼'd'和這些自定義'1'值是什麼意思? –

+0

對不起,我錯過了代碼的開頭,只是有更好的方法來檢查nots和nulls(也許在一個語句中)或任何東西,或者這是一個很好的linq聲明? Thans – AlexW

+1

它有什麼問題? – cadrell0

回答

2

幾點建議:

  1. 不要做.AsEnumerable,除非絕對必要,因爲它會導致 濾波做客戶端而不是數據庫 (你想要的地方)。
  2. 評估LINQ之外的常量。 (對於 例如你正在做的,你是 評估各行的Convert.ToDateTime(tblEquipments感謝每行上述第1期)。
  3. 假設發展,已刪除,股票和DecommissionDate是 空的,你可以嘗試.GetValueOrDefault(0),而不是價值!= 1 || 值== NULL。(注意,這取決於你的ORM提供商 支持這個結構和你修復#1以上。
  4. 做你的空性之前 測試比較,否則在嘗試將空值與值進行比較時,運行時上的代碼可能會失敗
0

試試這個:

DateTime decomission = Convert.ToDateTime("1900-01-01") 
db.tblEquipments.Include(t => t.User).Include(t => t.ChangeLog).AsEnumerable() 
    .Select(d => new { Object = d, ToCheck = 
            new[] { d.Development, d.Deleted, d.Stock }}) 
    .Where(a => a.ToCheck.All(x => x == null || x != 1) && 
        (a.Object.DecommissionDate == decomission || 
        a.Object.Decommission == null)) 
    .Select(a => a.Object); 
+1

耶穌!我認爲我的版本比那個更容易閱讀 – AlexW

+0

@AlexW我並不期望它複雜:P –

相關問題