問題描述
我正在從數據庫中提取 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();
您也可以像其他人所說的那樣使用空合并運算符 - 因為沒有人給出適用于您的代碼的示例,這里是一個:
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.
這篇關于檢查空值的最短方法,如果不是,則分配另一個值的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!