![](/img/trans.png)
[英]C# - How to give a default value using LINQ when the value returned is null
[英]C#: LINQ: If Null assign default value
我有一個 string[] 字段為 {prop1 = val1, prop2 = val2, amount = 30.00}。 我嘗試按如下方式獲取金額的值:
TransactionAmount = fields?.FirstOrDefault(x => x.ToLower().Contains("amount"))?.Split('=')[1].ToString();
如果金額(非字段)為空,如何分配默認值?
TransactionAmount = fields?.FirstOrDefault(x => x.ToLower().Contains("amount"))?.Split('=')[1].ToString() : "0.00"; //this is not working
謝謝
使用空合並運算符。 (或 ?? 運算符)
下面兩個是一樣的:
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
檢查數組是否為空:
//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];
並檢查 FirstOrDefault 是否返回 null:
(fields.FirstOrDefault(x => x.ToLower().Contains("amount")) ?? "DEFAULT_VALUE").Split('=')[1];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.