Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net C# String.Join how to output "null" instead of empty string if element value is null?

Tags:

string

c#

.net

null

According to the MSDN docs for String.Join "If any element in value is null, an empty string is used instead."

The code I have pulls data out of a DataTable

rotationValues = string.Join<object>(", ",
    from r in rotationData.Rows.OfType<DataRow>() select r[5]);

This would result in output similar to this:

8, 7, , 12, , , 13, 

Is there any way to simply have it put "null" in place of an empty string like so:

8, 7, null, 12, null, null, 13, null
like image 430
Reality Extractor Avatar asked May 18 '13 06:05

Reality Extractor


1 Answers

You can select

r[5] ?? "null"

instead of just r[5].

Also, just remove the <object> part when you call the generic method. It will still be an IEnumerable<object> that you join, but the compiler will infer the type parameter automatically.

ADDITION after comment:

Your r[5] might be DBNull.Value. Then, this is not a "real" null reference, but its ToString implementation returns "". So in that case, the string.Join documentation wasn't strictly relevant. Therefore, try to select something like

(r[5] == null || DBNull.Value.Equals(r[5])) ? "null" : r[5]

or maybe

(r[5] == null || r[5] is DBNull) ? "null" : r[5]

Hope it helps.

like image 173
Jeppe Stig Nielsen Avatar answered Oct 01 '22 21:10

Jeppe Stig Nielsen