我有這個代碼。
DisplayTimeStamp = PredictionTableList
.Where(x => x.ContextTimestamp != null)
.Select(x => x.ContextTimestamp)
.FirstOrDefault();
它回傳表的第一個資料。有時PredictionTableList為空,我如何檢查這一點并將空值回傳為“-”?
uj5u.com熱心網友回復:
選項 1:if-else檢查是否PredictionTableList是的陳述句null。
if (PredictionTableList == null)
DisplayTimeStamp = "-";
else
DisplayTimeStamp = PredictionTableList.Where(x => x.ContextTimestamp != null)
.Select(x => x.ContextTimestamp)
.FirstOrDefault();
選項 2:三元運算子
DisplayTimeStamp = PredictionTableList == null
? "-"
: PredictionTableList.Where(x => x.ContextTimestamp != null)
.Select(x => x.ContextTimestamp)
.FirstOrDefault();
uj5u.com熱心網友回復:
如果您使用的是 C# >= 版本 6,請使用以下?運算子:
DisplayTimeStamp = PredictionTableList?
.Where(x => x.ContextTimestamp != null)?
.Select(x => x.ContextTimestamp)?
.FirstOrDefault();
如果 PredictionTableList 是nullDisplayTimeStamp 將是null. 不會執行其他代碼。
uj5u.com熱心網友回復:
像這樣的東西:
DisplayTimeStamp = PredictionTableList?.Where(x => x.ContextTimestamp != null) .Select(x => x.ContextTimestamp).FirstOrDefault() ?? "-";
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-coalescing-operator
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/member-access-operators#null-conditional-operators--and-
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/522808.html
標籤:C#。网林克
