这是一个后续问题.Net C#的string.join如何输出零,而不是空字符串,如果元素值为null?如果答案建议使用 ??
运营商定义自定义的空值,但更换从未被触发。
This is a follow-up question to .Net C# String.Join how to output "null" instead of empty string if element value is null? where the answer suggested to use the ??
operator to define a custom null value, but the replacement never got triggered.
DataSet myDataSet = new DataSet();
mySqlDataAdapter.Fill(myDataSet);
DataTable rotationData = myDataSet.Tables["Table"];
rotationValues = string.Join(", ",
from r in rotationData.Rows.OfType<DataRow>()
select r[5] ?? "null");
当我改变code到:
rotationValues = string.Join(", ",
from r in rotationData.Rows.OfType<DataRow>()
select r[5].GetType());
我可以观察到,对于具有有效数据在他们的元素数据类型是 System.Double
,而对于它们是空的元素数据类型是 System.DBNull
。请问 ??
不是 System.DBNull
?
I can observe that the data type for elements that have valid data in them is System.Double
whereas the data type for elements which are NULL is System.DBNull
. Does ??
not operate on System.DBNull
?
没有的DBNull
和空
不是一样。
但是你可以这样写:
No DBNull
and null
is not the same thing.
But you can write this instead:
select r[5] == DBNull.Value ? "null" : r[5]);
另一种可能性是使用字段
扩展方法,它会给你指定行中每个列值的强类型的访问,而 ??
操作员工作。
Another possibility is to use Field
extension method, it will give you strongly-typed access to each of the column values in the specified row, and the ??
operator will work.
select r.Field<string>(5) ?? "null";