?? operator didn't trigger System.DBNull type in DataTable DataRow

筅森魡賤 提交于 2019-12-23 15:56:27

问题


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");

When I change the code to:

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

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?


回答1:


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";



回答2:


?? operates on the programming language null, not on the database DBNull.

From MSDN:

Do not confuse the notion of null in an object-oriented programming language with a DBNull object. In an object-oriented programming language, null means the absence of a reference to an object. DBNull represents an uninitialized variant or nonexistent database column.



来源:https://stackoverflow.com/questions/16621962/operator-didnt-trigger-system-dbnull-type-in-datatable-datarow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!