Is there a neat way to compare objects with NULL and dbnullable capabilities?

I have a code like this:

foreach (DataRow row in dataTable.Rows) { if ((string)row["Forename"] != record.Forename) { // Do something } } 

Works row["Forename"] , but if row["Forename"] is null in the database, it is actually DBNull here and it cannot distinguish DBNull from a row or perform a comparison between DBNull and string , some values ​​are also nullable<int> and it cannot compare DBNull with int?

Is there a helper method that allows me to make good comparisons, or do I need to write an extension method myself?

+6
source share
2 answers

You can use the DataRow.Field extension DataRow.Field , which supports DataRow.Field types:

 foreach (DataRow row in dataTable.Rows) { int? id = row.Field<int?>("ID"); if(id.HasValue) { Console.Write("ID: " + id.Value); } } 

Since string is a reference type, it will be null by default. You can use DataRow.IsNull to check if it is DBNull.Value or not:

 foreach (DataRow row in dataTable.Rows) { if(row.IsNull("Forename")) { // ... } else { string foreName = row.Field<string>("Forename"); Console.Write("ForeName: " + foreName); } } 
+5
source

You can write your own extension method like this

 public static T GetField<T>(this DataRow row,string columnName) { object value = row[columnname]; return (value != DbNull.Value)? (T)value : default(T); } 

Then you can use

 if (row.GetField<string>(columnname) != record.Forename) { // Do something } 

This extension must support nullable types as well

 var value = row.GetField<int?>(columnname); 

The only difference from DataRowExtension.Field and our implementation is that it will throw an exception when we try to use DbNull.Value for any value type (except for the NULL type), in which case this method will return the default value.

+1
source

Source: https://habr.com/ru/post/970195/


All Articles