2016-12-30 76 views
-1

我試圖用NULL Coalesce將幾個整數加在一起,其中至少有兩個整數可能爲爲NULL,在這種情況下,將0分配給這些整數,然後添加。第一個非空變量的空合併返回值

var total = votes[0].Value ?? 0 + votes[1].Value ?? 0 + votes[2].Value ?? 0 + votes[3].Value ?? 0; 

total返回votes[0].Value,而不是另外四個變量的值。

有沒有一種方法可以得到所有整數的總和?

+0

你確定數組有你認爲它的值嗎?如果你打破它,並檢查它們的值... –

+0

是的,當我在調試器中通過時。 – hello

+3

[C#空合併(??)運算符的運算符優先級是什麼?](可能重複的問題](http://stackoverflow.com/questions/511093/what-is-the-operator-precedence-of-c-sharp -null-coalescing-operator) –

回答

1

該代碼等同於:

var total = votes[0].Value ?? (0 + votes[1].Value ?? (0 + votes[2].Value ?? (0 + votes[3].Value ?? 0))); 

因此,它應該是相當明顯的,現在爲什麼它返回votes[0].Value,而不是所有的非空值的總和。

1

如果爲空整數數組,你可以這樣寫:

var votes = new int?[] {1, 2, 3, 4}; 
var total = (votes[0] ?? 0) + (votes[1] ?? 0) + (votes[2] ?? 0) + (votes[3] ?? 0); 
0

這是清潔劑,它會跳過空值:

var total = votes.Sum(); 
+0

'votes.Sum()'更清潔。 – PetSerAl

+0

謝謝。我認爲這不適用於空值,但它確實如此。 – CodingYoshi

4
var total = votes.Sum(); 

它會算空值爲零。

+1

「空值爲零」:雖然這對於「Sum」有效,但更通用的說它跳過空值。這樣,它也適用於「平均」等。 (但是,當然不是「伯爵」。) –