[英]How can I default a value set inside a Tuple to be “n/a” if it is null?
我有這個C#代碼:
var result =
from entry in feed.Descendants(a + "entry")
let content = entry.Element(a + "content")
let properties = content.Element(m + "properties")
let notes = properties.Element(d + "Notes")
let title = properties.Element(d + "Title")
let partitionKey = properties.Element(d + "PartitionKey")
where partitionKey.Value.Substring(2, 2) == "06" && title != null && notes != null
select new Tuple<string, string>(title.Value, notes.Value);
僅當我選擇注釋時才有效!= null
而不是這樣做,如果notes.Value為null,那么如何在元組中將notes.Value的值設置為“ n / a”?
您可以使用null合並運算符 ??
select new Tuple<string, string>(title.Value, notes.Value ?? "n/a");
注意,您也可以使用Tuple.Create
代替tuple構造函數:
select Tuple.Create(title.Value, notes.Value ?? "n/a");
如果是Enumerable String
,則可以在let
表達式級別使用null合並運算符,如果為null則使用默認值
let notes = properties.Element(d + "Notes") ?? "n/a"
let title = properties.Element(d + "Title") ?? "n/a"
然后將where子句重寫為
where partitionKey.Value.Substring(2, 2) == "06"
select new Tuple<string, string>(title.Value, notes.Value);
如前所述,在XElement的情況下,您可以選擇
where partitionKey.Value.Substring(2, 2) == "06"
select new Tuple<string, string>(title.Value??"n/a", notes.Value??"n/a");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.