Alan2
Alan2

Reputation: 24572

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?

Upvotes: 1

Views: 395

Answers (3)

S.N
S.N

Reputation: 5140

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");

Upvotes: 1

Lee
Lee

Reputation: 144136

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");

Upvotes: 2

Grant Thomas
Grant Thomas

Reputation: 45083

You can use the null coalescing operator:

notes.Value ?? "n/a"

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

Upvotes: 7

Related Questions