简体   繁体   中英

Null Coalesce returning value of first non null variable

I'm trying to add several integers together using NULL Coalesce , in which at least 2 of the integers may be NULL, in that case, assign 0 to such integers and then add.

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

total returns the value of votes[0].Value instead of addition of all four variables.

Is there a way I can get the total of all the integers?

var total = votes.Sum();

它将空值计为零。

That code is equivalent to:

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

So it should be rather apparent now why it returns votes[0].Value rather than the sum of all of the non-null values.

If votes is an array of nullable integers you can write:

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM