How to print the null values if the dictionary has it using LINQ

假如想象 提交于 2020-07-22 05:58:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!