SoftwareDveloper
SoftwareDveloper

Reputation: 742

C#: LINQ: If Null assign default value

I have a string[] fields as {prop1 = val1, prop2 = val2, amount = 30.00}. And I try to get the value of amount as follows:

TransactionAmount = fields?.FirstOrDefault(x => x.ToLower().Contains("amount"))?.Split('=')[1].ToString();

How do I assign a default value if amount(not fields)is null?

TransactionAmount = fields?.FirstOrDefault(x => x.ToLower().Contains("amount"))?.Split('=')[1].ToString() : "0.00"; //this is not working

Thank you

Upvotes: 0

Views: 1117

Answers (1)

Tommy
Tommy

Reputation: 359

Use the null-coalescing operator. (or the ?? operator)

The two below are the same:

return A ?? B;//Using the null-coalescing operator.

if (A == null) return B;//Using if-else.
else return A;

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-coalescing-operator

Check whether the array is null:

//Is Fields null? if not, use fields, otherwise, use the
//new string array with the "DEFAULT_VALUE".
(fields ?? new string[] { "DEFAULT_VALUE" }).FirstOrDefault(x => x.ToLower().Contains("amount")).Split('=')[1];

And check whether FirstOrDefault returned null:

(fields.FirstOrDefault(x => x.ToLower().Contains("amount")) ?? "DEFAULT_VALUE").Split('=')[1];

Upvotes: 2

Related Questions