【问题标题】:How to print the null values if the dictionary has it using LINQ如果字典使用 LINQ,如何打印空值
【发布时间】:2020-11-04 02:14:30
【问题描述】:

我有包含以下键和值的字典。我正在尝试打印字典,但在有空值的地方没有打印任何内容。如何在输出中打印“null”?

Dictionary<string, object> dic1 = new Dictionary<string, object>();
            dic1.Add("id", 1);
            dic1.Add("name", "john");
            dic1.Add("grade", null);

            Console.WriteLine(string.Join(Environment.NewLine, dic1.Select(a => $"{a.Key}: {a.Value}")));

这是我得到的输出:

id: 1
name: john
grade:

【问题讨论】:

    标签: c# dictionary null conditional-operator null-coalescing


    【解决方案1】:

    您可以在这种情况下使用null-coalescing operator (??),如果它不是null,它会返回其左侧操作数的值,否则它会评估右侧操作数并返回其结果.所以我们只需要在右边加上"null"即可:

    Console.WriteLine(string.Join(Environment.NewLine, 
        dic1.Select(a => $"{a.Key}: {a.Value ?? "null"}")));
    

    输出

    id: 1
    name: john
    grade: null
    

    【讨论】:

      【解决方案2】:

      您可以使用ternary conditional operator

      如果? 左边的表达式计算为true,则计算: 左边的表达式。如果false,则计算: 的右表达式。

      Console.WriteLine(string.Join(Environment.NewLine, dic1.Select(a => $"{a.Key}: {(a.Value == null ? "null" : a.Value)}")));
      

      上面的代码比前面提到的null-coalescing operator 稍微逊色。

      Console.WriteLine(string.Join(Environment.NewLine, dic1.Select(a => $"{a.Key}: {a.Value?? "null"}")));
      

      【讨论】:

        【解决方案3】:

        试一试。

        Console.WriteLine(string.Join(Environment.NewLine, dic1.Select(a => $"{a.Key}: {a.Value ?? "null"}")));
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-08-06
          • 2015-12-23
          • 1970-01-01
          • 1970-01-01
          • 2019-04-18
          • 1970-01-01
          • 2011-06-27
          • 1970-01-01
          相关资源
          最近更新 更多