问题
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:
回答1:
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
回答2:
Give this a whirl.
Console.WriteLine(string.Join(Environment.NewLine, dic1.Select(a => $"{a.Key}: {a.Value ?? "null"}")));
回答3:
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"}")));
来源:https://stackoverflow.com/questions/62900326/how-to-print-the-null-values-if-the-dictionary-has-it-using-linq