Linq query - dynamic data types
<p>I have a linq query working nicely to aggregate values from a DataTable.</p>

<p>The idea is that a user can select one of a list of fields, and the linq aggregates data according to the field selected.</p>

<p><strong>p_measure</strong> is a string variable denoting the name of a field selected.</p>

<p>However, in it's current form, this all only works when the selected field is of data type 'float' in the source table.
If the user selects an 'int' ... then I get a cast exception thrown.</p>

<p>So the question is, how do i make this code 'dynamic' to handle the varying datatypes ?</p>

<pre><code>// Table for receiving aggregated results 
var table = new DataTable();
table.Columns.Add(p_dimension, typeof(String));
table.Columns.Add(p_measure, typeof(Double));

// Query to perform aggregation
DataTable query = (from r in rootDT.AsEnumerable()
                   group r by new
                           {
                              Dimension = r.Field&lt;string&gt;(p_dimension)
                           } into g
                             select new
                           {
                              Dimension = g.Key.Dimension,
                              Measure = g.Sum(x =&gt; x.Field&lt;double&gt;(p_measure))
                            }
                         ).Aggregate(table, (dt, r) =&gt; dt.Rows.Add(r.Dimension,r.Measure); return dt; });
</code></pre>

<p>I can handle the type in the "new DataTable" declaration (line 4):</p>

<pre><code>table.Columns.Add(p_measure, typeof(Double));
</code></pre>

<p>by generating &amp; setting a variable of type Type, thus : </p>

<pre><code>table.Columns.Add(p_measure, myTypeVariable);
</code></pre>

<p>But I am at a loss how to handle this one:</p>

<pre><code>x.Field&lt;double&gt;(p_measure)
</code></pre>

<p>Any ideas ??</p>