Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 647
Reality Extractor Avatar asked Dec 26 '22 03:12

Reality Extractor


1 Answers

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";
like image 72
Magnus Avatar answered Jan 13 '23 23:01

Magnus