[英]How can I default a value set inside a Tuple to be “n/a” if it is null?
I have this C# code: 我有这个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);
It works only if I select notes != null 仅当我选择注释时才有效!= null
Rather than do this how can I set the value of notes.Value in the Tuple to be "n/a" if notes.Value is a null? 而不是这样做,如果notes.Value为null,那么如何在元组中将notes.Value的值设置为“ n / a”?
You can use the null coalescing operator : 您可以使用null合并运算符 :
notes.Value ?? "n/a"
Which says "get the value if not null, otherwise use the secondary argument." 上面写着“如果不为null,则获取该值,否则使用第二个参数。”
You can use the null coallescing operator ??
您可以使用null合并运算符 ??
select new Tuple<string, string>(title.Value, notes.Value ?? "n/a");
Note you can also use Tuple.Create
instead of the tuple constructor: 注意,您也可以使用Tuple.Create
代替tuple构造函数:
select Tuple.Create(title.Value, notes.Value ?? "n/a");
In case of Enumerable String
, you can use null coalescing operator at the let
expression level to have default in case of null 如果是Enumerable String
,则可以在let
表达式级别使用null合并运算符,如果为null则使用默认值
let notes = properties.Element(d + "Notes") ?? "n/a"
let title = properties.Element(d + "Title") ?? "n/a"
then rewrite the where clause as 然后将where子句重写为
where partitionKey.Value.Substring(2, 2) == "06"
select new Tuple<string, string>(title.Value, notes.Value);
As pointed, in case of XElement, you can alternately have 如前所述,在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.