title: Convert IEnumerable to DataTable
body: <p>Is there a nice way to convert an IEnumerable to a DataTable?</p>
  
  <p>I could use reflection to get the properties and the values, but that seems a bit inefficient, is there something build-in?</p>
  
  <p><em>(I know the examples like: ObtainDataTableFromIEnumerable)</em></p>
  
  <p><strong>EDIT</strong>:<br>
  This <a href="https://stackoverflow.com/questions/2169157/linq-to-dataset-handling-null-values">question</a> notified me of a problem handling null values.<br>
  The code I wrote below handles the null values properly.</p>
  
  <pre><code>public static DataTable ToDataTable&lt;T&gt;(this IEnumerable&lt;T&gt; items) {  
      // Create the result table, and gather all properties of a T        
      DataTable table = new DataTable(typeof(T).Name); 
      PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);  
  
      // Add the properties as columns to the datatable
      foreach (var prop in props) { 
          Type propType = prop.PropertyType; 
  
          // Is it a nullable type? Get the underlying type 
          if (propType.IsGenericType &amp;&amp; propType.GetGenericTypeDefinition().Equals(typeof(Nullable&lt;&gt;))) 
              propType = new NullableConverter(propType).UnderlyingType;  
  
          table.Columns.Add(prop.Name, propType); 
      }  
  
      // Add the property values per T as rows to the datatable
      foreach (var item in items) {  
          var values = new object[props.Length];  
          for (var i = 0; i &lt; props.Length; i++) 
              values[i] = props[i].GetValue(item, null);   
  
          table.Rows.Add(values);  
      } 
  
      return table; 
  } 
  </code></pre>