简体   繁体   English

第一个非null变量的null合并返回值

[英]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. 我正在尝试使用NULL Coalesce将多个整数加在一起,其中至少2个整数可能为NULL,在这种情况下,将0分配给此类整数,然后相加。

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. total返回的是votes[0].Value的值,而不是所有四个变量的和。

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. 因此,现在应该很明显为什么它返回votes[0].Value而不是所有非空值的总和。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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