检查null并分配另一个值的最短方法 [英] Shortest way to check for null and assign another value if not
问题描述
我要从数据库中提取 varchar
值,并希望将 string
设置为如果为 null
,则为。我目前正在这样做:
I am pulling varchar
values out of a DB and want to set the string
I am assigning them to as "" if they are null
. I'm currently doing it like this:
if (string.IsNullOrEmpty(planRec.approved_by) == true)
this.approved_by = "";
else
this.approved_by = planRec.approved_by.toString();
似乎应该有一种方法可以像这样:
There seems like there should be a way to do this in a single line something like:
this.approved_by = "" || planRec.approved_by.toString();
但是我找不到最佳的方法。有更好的方法还是我有最好的方法?
However I can't find an optimal way to do this. Is there a better way or is what I have the best way to do it?
推荐答案
尝试一下:
this.approved_by = IsNullOrEmpty(planRec.approved_by) ? "" : planRec.approved_by.toString();
您也可以使用null-coalescing运算符,因为没有人举过例子适用于您的代码的代码是一个:
You can also use the null-coalescing operator as other have said - since no one has given an example that works with your code here is one:
this.approved_by = planRec.approved_by ?? planRec.approved_by.toString();
但该示例仅适用于 this.approved_by
与您希望将其设置为的潜在值之一相同。对于所有其他情况,您将需要使用我在第一个示例中显示的条件运算符。
But this example only works since a possible value for this.approved_by
is the same as one of the potential values that you wish to set it to. For all other cases you will need to use the conditional operator as I showed in my first example.
这篇关于检查null并分配另一个值的最短方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!