簡體   English   中英

如果它為空,如何在元組中默認將值設置為“ n / a”?

[英]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合並運算符

notes.Value ?? "n/a"

上面寫着“如果不為null,則獲取該值,否則使用第二個參數。”

您可以使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM