1

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}")));

Here is the output I get:

id: 1
name: john
grade:
Super Jade
  • 5,609
  • 7
  • 39
  • 61
KevinDavis965
  • 39
  • 1
  • 8

3 Answers3

5

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"}")));

Output

id: 1
name: john
grade: null
Super Jade
  • 5,609
  • 7
  • 39
  • 61
Rufus L
  • 36,127
  • 5
  • 30
  • 43
2

Give this a whirl.

Console.WriteLine(string.Join(Environment.NewLine, dic1.Select(a => $"{a.Key}: {a.Value ?? "null"}")));
Merkle Groot
  • 846
  • 5
  • 9
0

You could use the ternary conditional operator.

If the expression left of the ? evaluates to true, the expression left of the : is evaluated. If false, the expression right of the : is evaluated.

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

The above is somewhat less elegant than the null-coalescing operator already mentioned.

Console.WriteLine(string.Join(Environment.NewLine, dic1.Select(a => $"{a.Key}: {a.Value?? "null"}")));
Super Jade
  • 5,609
  • 7
  • 39
  • 61