[英]Linq compare nullable string to string
我有以下LINQ:
var items = from n in db.Roles
where n.importID == importID
select n;
“ importID”是一個字符串作為參數和一個字符串? 用於數據庫對象。 如果importID在數據庫中為null,則不存在匹配項。 如何實現呢?
編譯器消息:
Operator '==' cannot be applied to operands of type 'string?' and 'string'
字符串是引用類型,因此已經可以為空(即,可以將其設置為null)。 Nullable類型的唯一目的是允許將值類型(例如整數,雙精度型等)設置為null。 解決方法是將importId
聲明為string
,而不是string?
。
var items = from n in db.Roles
where n.importID.HasValue && n.importId.Value == importID
select n;
您也可以使用.GetValueOrDefault()
總之查詢可以...
var items = from n in db.Roles
where n.importID == importID.GetValueOrDefault()
select n;
var items = from n in db.Roles
where !string.IsNullOrEmpty(n.importID) && n.importID == importID
select n;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.