简体   繁体   中英

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

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://docs.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];

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