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

前端 未结 11 2306
伪装坚强ぢ
伪装坚强ぢ 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 01:53

    To assign a non-empty variable without repeating the actual variable name (and without assigning anything if variable is null!), you can use a little helper method with a Action parameter:

    public static void CallIfNonEmpty(string value, Action action)
    {
        if (!string.IsNullOrEmpty(value))
            action(value);
    }
    

    And then just use it:

    CallIfNonEmpty(this.approved_by, (s) => planRec.approved_by = s);
    

提交回复
热议问题