c# - 检查 NameValueCollection 是否有值(value)的最优雅的方法

标签 c# namevaluecollection

我有一行简单的代码:lead.InternalCompany = nvCollection["ic"];

我想将 lead.InternalCompany 设置为检索到的值,但如果没有空字符串 ""

我尝试使用 nvCollection["ic"].HasValue();

我知道我可以做这样简单的事情

string value = nvCollection["ic"];
if (value == null) // key doesn't exist
    {
        lead.InternalCompany = "";
    }

理想情况下,我希望使用三元 if 语句 来完成此操作

最佳答案

使用 null-coalescing operator

The ?? operator is called the null-coalescing operator and is used to define a default value for nullable value types or reference types. It returns the left-hand operand if the operand is not null; otherwise it returns the right operand.

lead.InternalCompany = nvCollection["ic"] ?? string.Empty;

关于c# - 检查 NameValueCollection 是否有值(value)的最优雅的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18383892/

相关文章:

c# - 如何在 C# 中模拟基类属性或方法

c# - 没有值的 NameValueCollection 键

c# - 检查 Key 是否存在于 NameValueCollection 中

c# - 依赖任务图 : neat parallel execution in . 网络?

c# - 将 HttpCookieCollection 转换为 NameValueCollection

java - 将 URI 字符串解析为名称-值集合

c# - 有什么简单的方法可以根据 C# 中的键对 NameValueCollection 进行排序?

c# - 使用 Linq c# 将 List<A> 转换为 List<B>

c# - "Must be already floating point"将音频文件转换为 wav 文件时

c# - 我们什么时候需要使用代理类?