本文介绍了如果字典使用LINQ有空值,如何打印空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有带以下键和值的字典。我正在尝试打印字典,但是在有空值的地方什么也不会打印。如何打印 null

I have dictionary with the following keys and values. I am trying to print the dictionary, but nothing prints where there is a null value. How do I print "null" in the output?

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,则返回其左操作数的值$ c> null ,否则它将评估右侧操作数并返回其结果。因此,我们只需要在右侧添加 null

You can use the null-coalescing operator (??) in this situation, which returns the value of its left-hand operand if it isn't null, otherwise it evaluates the right-hand operand and returns its result. So we only need to add "null" to the right hand side:

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

输出

id: 1
name: john
grade: null

这篇关于如果字典使用LINQ有空值,如何打印空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-02 01:03