Shortest way to check for null and assign another value if not

前端 未结 11 2166
伪装坚强ぢ
伪装坚强ぢ 2020-12-13 01:32

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 doi

相关标签:
11条回答
  • 2020-12-13 02:00

    Use the C# coalesce operator: ??

    // if Value is not null, newValue = Value else if Value is null newValue is YournullValue
    var newValue = Value ?? YourNullReplacement;
    
    0 讨论(0)
  • 2020-12-13 02:07

    Try this:

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

    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.

    0 讨论(0)
  • 2020-12-13 02:07

    You can also do it in your query, for instance in sql server, google ISNULL and CASE built-in functions.

    0 讨论(0)
  • 2020-12-13 02:11

    The coalesce operator (??) is what you want, I believe.

    0 讨论(0)
  • 2020-12-13 02:16

    With C#6 there is a slightly shorter way for the case where planRec.approved_by is not a string:

    this.approved_by = planRec.approved_by?.ToString() ?? "";
    
    0 讨论(0)
提交回复
热议问题