如何将Tuple中的值设置默认为"n/a"如果为空

本文关键字:quot 如果 默认 Tuple 设置 | 更新日期: 2023-09-27 18:19:17

我有这个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

不这样做,我如何设置笔记的值。如果注意,元组中的值为"n/a"。值是空的?

如何将Tuple中的值设置默认为"n/a"如果为空

可以使用空合并运算符:

notes.Value ?? "n/a"

表示"如果不为空则获取值,否则使用次要参数"。

您可以使用null合并操作符??

select new Tuple<string, string>(title.Value, notes.Value ?? "n/a");

注意您也可以使用Tuple.Create来代替元组构造函数:

select Tuple.Create(title.Value, notes.Value ?? "n/a");

对于Enumerable String,可以在let表达式级别使用空合并运算符,以在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");