简体   繁体   中英

How can I default a value set inside a Tuple to be “n/a” if it is null?

I have this C# code:

        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

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?

You can use the null coalescing operator :

notes.Value ?? "n/a"

Which says "get the value if not null, otherwise use the secondary argument."

You can use the null coallescing operator ??

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

Note you can also use Tuple.Create instead of the tuple constructor:

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

let notes = properties.Element(d + "Notes") ?? "n/a"
 let title = properties.Element(d + "Title") ?? "n/a"

then rewrite the where clause as

  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

    where partitionKey.Value.Substring(2, 2) == "06"
    select new Tuple<string, string>(title.Value??"n/a", notes.Value??"n/a");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM