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
You can select
instead of just
r[5]
.Also, just remove the
<object>
part when you call the generic method. It will still be anIEnumerable<object>
that you join, but the compiler will infer the type parameter automatically.ADDITION after comment:
Your
r[5]
might beDBNull.Value
. Then, this is not a "real" null reference, but itsToString
implementation returns""
. So in that case, thestring.Join
documentation wasn't strictly relevant. Therefore, try to select something likeor maybe
Hope it helps.
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 typeSystem.DBNull
yet it didn't do the replacement with "null".Here is what I ended up doing instead:
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 notDBNull
. See also .Net C# ?? operator didn't trigger for System.DBNull type in DataTable DataRow