我有这个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”?
答案 0 :(得分:7)
答案 1 :(得分:2)
您可以使用null coallescing operator ??
select new Tuple<string, string>(title.Value, notes.Value ?? "n/a");
注意,您也可以使用Tuple.Create
代替元组构造函数:
select Tuple.Create(title.Value, notes.Value ?? "n/a");
答案 2 :(得分:1)
如果是Enumerable String
,您可以在let
表达式级别使用空合并运算符,以便在为空时保留默认值
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");