问题
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
回答1:
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.
回答2:
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
来源:https://stackoverflow.com/questions/16621347/net-c-sharp-string-join-how-to-output-null-instead-of-empty-string-if-element