在此示例中,我有一個可為空的 int 并且在 lambda 中我想將其設定為 0,然后進行比較。如果null我想將其設定為0然后將其設定為 <= 1. lambda where條件中的HasValue如何?
var exchangeAttemptsList = ExchangeRequestList
.Where( x => x.ExchangeAttempts.HasValue
? x.ExchangeAttempts.Value
: 1 <= 1
)
.ToList()
;
樣本
https://dotnetfiddle.net/f5BD4n
uj5u.com熱心網友回復:
這個運算式沒有意義(并且不編譯):
x => x.ExchangeAttempts.HasValue
? x.ExchangeAttempts.Value
: 1 <= 1
那是完全等價的(假設ExchangeAttempts是int?:
int lambda( x MyClass )
{
int result;
if ( x.ExchangeAttempts.HasValue )
{
result = x.ExchangeAttempts.Value ;
}
else
{
result = 1 <= 1 ;
}
return result;
}
它無法編譯,因為運算式的1 <= 1計算結果為true。
如果您要做的是分配默認值1if ExchangeAttemptsis null,只需說:
x => (x.ExchangeAttempts ?? 1) <= 1
它更短更簡潔,更好地表達你的意圖。
或者,更好的是:
x => x.ExchangeAttempts == null || x.ExchangeAttempts <= 1
邏輯運算式短路,因此僅在第一次測驗失敗時才嘗試替代方法,因此上述回傳true時
x.ExchangeAttempts沒有價值,或x.ExchangeAttempts具有小于或等于 1 的值
并回傳false時
x.ExchangeAttempts有一個值,并且該值 > 1。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/481534.html
