title: C# function to cast multiple datarow values as null if dbnull is detected
body: <p>My Linq-to-SQL program is returning quite a few values from my SQL Server database some of which the values can be null and others not. </p>
  
  <p>If the <code>DataTable</code> column is cast as string, this is not an issue. However when it is cast as decimal, I get error messages stating decimal cannot be null. </p>
  
  <p>What I need to find out is how I can handle these effectively whilst keeping my code neat.</p>
  
  <pre><code>// Create DataTable
  DataTable dt = new DataTable();
  dt.Columns.add("Deal", typeof(string));
  dt.Columns.add("Price", typeof(decimal) ?? typeof(DBNull));
  
  // Create Linq Query
  var query =
      from quer in table 
      select new  
      {
          quer.deal_id,
          quer.price 
      };
  </code></pre>
  
  <p>Here I create my datarows before inserting into the table:</p>
  
  <pre><code>var datarows = query.Select(r =&gt;
  {
      var row = dt.NewRow();
      row["Deal"] = r.deal_id;
      row["Price"] = r.price;
  };
  </code></pre>
  
  <p>Now to ensure that my datarow can handle Nulls, I can just make it nullable but it's not necessary.</p>
  
  <pre><code>dt.Columns.add("Deal", typeof(string?));
  </code></pre>
  
  <p>But for the decimal field I have to do this:</p>
  
  <pre><code>if (r.price == DBNull.Value)
  {
      row["Price"] = null;
  }
  </code></pre>
  
  <p>Now I have to do about 50 of these <code>if</code> statement checks per table I'm designing. Can I just pass it to a function to do?</p>