Reality Extractor
Reality Extractor

Reputation: 1277

.Net C# String.Join how to output "null" instead of empty string if element value is 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

Upvotes: 5

Views: 5173

Answers (2)

Reality Extractor
Reality Extractor

Reputation: 1277

To expand on Jeppe's answer, I am not sure why his way didn't actually work for me, I confirmed that the null values in r[5] are actually of type System.DBNull yet it didn't do the replacement with "null".

Here is what I ended up doing instead:

rotationValues = string.Join(", ",
    from r in rotationData.Rows.OfType<DataRow>()
    select (r[5].ToString().Length == 0 ? "null" : r[5]));

Which is a conditional that I didn't want to do, but I had a look at this page C# Empty Strings where the guy benchmarked different ways to check whether a string is empty and the length method was the fastest. So I figured to check for the length and join "null" if the length is 0 and the actual r[5] value when it is not zero.

It would still be good to figure out why ?? "null" didn't work though.

EDIT FOR REFERENCE: The issue is indeed that ?? operates on null and not DBNull. See also .Net C# ?? operator didn't trigger for System.DBNull type in DataTable DataRow

Upvotes: 0

Jeppe Stig Nielsen
Jeppe Stig Nielsen

Reputation: 61950

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.

Upvotes: 8

Related Questions