[英]Null Coalesce returning value of first non null variable
我正在嘗試使用NULL Coalesce
將多個整數加在一起,其中至少2個整數可能為NULL,在這種情況下,將0分配給此類整數,然后相加。
var total = votes[0].Value ?? 0 + votes[1].Value ?? 0 + votes[2].Value ?? 0 + votes[3].Value ?? 0;
total
返回的是votes[0].Value
的值,而不是所有四個變量的和。
有沒有辦法可以獲取所有整數的總和?
var total = votes.Sum();
它將空值計為零。
該代碼等效於:
var total = votes[0].Value ?? (0 + votes[1].Value ?? (0 + votes[2].Value ?? (0 + votes[3].Value ?? 0)));
因此,現在應該很明顯為什么它返回votes[0].Value
而不是所有非空值的總和。
如果表決是可空整數的數組,則可以編寫:
var votes = new int?[] {1, 2, 3, 4};
var total = (votes[0] ?? 0) + (votes[1] ?? 0) + (votes[2] ?? 0) + (votes[3] ?? 0);
這樣比較干凈,它將跳過空值:
var total = votes.Sum();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.