Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Your problem is this:</p> <pre><code>as IEnumerable&lt;DataRow&gt; </code></pre> <p>The <code>as</code> keyword performs a safe cast, not a conversion, which it seems like you might think that it's doing. The <code>as</code> keyword is semantically the same as doing this:</p> <pre><code>IEnumerable&lt;DataRow&gt; queryProjects = (IEnumerable&lt;DataRow&gt;)(from DataRow p in db.STREAM_PROJECTs.AsEnumerable() where p.Field&lt;int&gt;("STREAM_ID") == StreamID select new { PROJECT_ID = p.Field&lt;int&gt;("PROJECT_ID"), PROJECT_NAME = p.Field&lt;int&gt;("PROJECT_NAME") }); </code></pre> <p>Except the version with <code>as</code> won't throw an exception when it fails to cast your query object (which is an <code>IQueryable&lt;T&gt;</code>, where <code>T</code> is an anonymous type) to an <code>IEnumerable&lt;DataRow&gt;</code> (which it isn't).</p> <p>Unfortunately, there is no built-in method that I'm aware of that will take an enumerable of a concrete type (like your anonymous type in this example) and turn it into a <code>DataTable</code>. Writing one wouldn't be too complicated, as you'd essentially need to get the properties reflectively then iterate over the collection and use those properties to create columns in a <code>DataTable</code>. I'll post an example in a few.</p> <p>Something like this, placed in a static class within a namespace that you're <code>using</code>, should provide an extension method that will do what you want:</p> <pre><code>public static DataTable ToDataTable&lt;T&gt;(this IEnumerable&lt;T&gt; source) { PropertyInfo[] properties = typeof(T).GetProperties(); DataTable output = new DataTable(); foreach(var prop in properties) { output.Columns.Add(prop.Name, prop.PropertyType); } foreach(var item in source) { DataRow row = output.NewRow(); foreach(var prop in properties) { row[prop.Name] = prop.GetValue(item, null); } output.Rows.Add(row); } return output; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload