我有問題 - 如何檢查where條款中的條件,即使項目沒有參考?Linq - 檢查where條款中的條件,如果字段可以爲空
最基本的方法 - 我從我的類中檢查字段,它可以爲null。當我剛剛檢查它以這種方式它會返回空引用異常
var soldOutProducts = from p in list
where p.destinataire.StartsWith("D")
select p;
我有問題 - 如何檢查where條款中的條件,即使項目沒有參考?Linq - 檢查where條款中的條件,如果字段可以爲空
最基本的方法 - 我從我的類中檢查字段,它可以爲null。當我剛剛檢查它以這種方式它會返回空引用異常
var soldOutProducts = from p in list
where p.destinataire.StartsWith("D")
select p;
你可以做的
var soldOutProducts = from p in list
where !string.IsNullOrEmpty(p.destinataire) and
p.destinataire.StartsWith("D")
select p;
只是檢查空第一,就像你,如果你是在一個循環中寫正常的C#代碼。
where p.destinataire != null && p.destinataire.StartsWith("D")
如果p
本身可以爲空(即你的列表可以包含null元素),那麼你需要檢查它:
where p != null && p.destinataire != null && p.destinataire.StartsWith("D")
請注意,如果您的查詢表達式是只是做濾波,您可能需要使用點符號代替:
var soldOutProducts = list.Where(p => p.destinataire != null &&
p.destinataire.StartsWith("D"));
查詢表達式在查詢獲取時非常有用複雜 - 尤其是連接和分組。
var soldOutProducts = from p in list
where p.destinataire != null && p.destinataire.StartsWith("D")
select p;
可能重複[LINQ:添加where子句僅當值不爲空(http://stackoverflow.com/questions/5787794/linq-adding- where-clause-when-a-value-is-not-null) – pravprab