[英]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.