C#最短的路径,以检查空和分配另一个值如果不 [英] C# Shortest Way to Check for Null and Assign Another Value if Not

查看:123
本文介绍了C#最短的路径,以检查空和分配另一个值如果不的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我拉VARCHAR值了DB的,并要设置,我给它们赋予的,如果他们是空的字符串。目前,我正在做这样的。

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

您也可以使用空合并运算符其他说 - 因为没有人给与您code在这里工作的例子就是一句:

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.

这篇关于C#最短的路径,以检查空和分配另一个值如果不的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆