检查空值的最短方法,如果不是,则分配另一个值

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

您也可以像其他人所说的那样使用空合并运算符 - 因为没有人给出适用于您的代码的示例,这里是一个:

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.

这篇关于检查空值的最短方法,如果不是,则分配另一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

ActiveDirectory error 0x8000500c when traversing properties(遍历属性时 ActiveDirectory 错误 0x8000500c)
search by samaccountname with wildcards(使用通配符按 samaccountname 搜索)
Get the list of Groups for the given UserPrincipal(获取给定 UserPrincipal 的组列表)
Can you find an Active Directory User#39;s Primary Group in C#?(你能在 C# 中找到 Active Directory 用户的主要组吗?)
How to register System.DirectoryServices for use in SQL CLR User Functions?(如何注册 System.DirectoryServices 以在 SQL CLR 用户函数中使用?)
Query From LDAP for User Groups(从 LDAP 查询用户组)