Convert DataTable columns to typed IEnumerable[]
<p>How to convert DataTable columns to IEnumerable[] which is required to create a data frame in R.NET</p>

<p>I have the following code:</p>

<pre><code>DataTable dt = CreateDateTable();
REngine e = REngine.GetInstance();                       
IEnumerable[] columns = new IEnumerable[dt.Columns.Count];                
string[] columnNames = dt.Columns.Cast&lt;DataColumn&gt;()
                       .Select(x =&gt; x.ColumnName)
                       .ToArray();

for(int i=0; i&lt;dt.Columns.Count; i++)
    //This is the place where I am stuck. How to convert column to base type array instead of object array
    columns[i] = dt.Rows.Cast&lt;DataRow&gt;().Select(row =&gt; row[i]).ToArray();

DataFrame df = e.CreateDataFrame(columns: columns, 
 columnNames: columnNames, 
 stringsAsFactors: false);
</code></pre>

<p>I get the following exception:</p>

<pre><code>Test 'XXX.ReadResultsTest' failed: System.NotSupportedException : Cannot convert type System.Object[] to an R vector
       w RDotNet.REngineExtension.ToVector(REngine engine, IEnumerable values)
       w System.Array.ConvertAll[TInput,TOutput](TInput[] array, Converter`2 converter)
       w RDotNet.REngineExtension.CreateDataFrame(REngine engine, IEnumerable[] columns, String[] columnNames, String[] rowNames, Boolean checkRows, Boolean checkNames, Boolean stringsAsFactors)
</code></pre>

<p><code>DataTable</code> has columns of different types and I don't know what are the types so I cannot do like in this example with <code>double</code>:</p>

<pre><code>for (int i = 0; i &lt; dt.Columns.Count; i++)
        columns[i] = dt.Rows.Cast&lt;DataRow&gt;().Select(row =&gt; row.Field&lt;double&gt;(i)).ToArray();
</code></pre>

<p><strong>UPDATE</strong></p>

<p>So far I have an ugly solution, can it be done better?</p>

<pre><code>for (int i = 0; i &lt; dt.Columns.Count; i++)
{
    switch (Type.GetTypeCode(dt.Columns[i].DataType))
    {
        case TypeCode.String:
            columns[i] = dt.Rows.Cast&lt;DataRow&gt;().Select(row =&gt; row.Field&lt;string&gt;(i)).ToArray();
            break;

        case TypeCode.Double:
            columns[i] = dt.Rows.Cast&lt;DataRow&gt;().Select(row =&gt; row.Field&lt;double&gt;(i)).ToArray();
            break;

        case TypeCode.Int32:
            columns[i] = dt.Rows.Cast&lt;DataRow&gt;().Select(row =&gt; row.Field&lt;int&gt;(i)).ToArray();
            break;

        case TypeCode.Int64:
            columns[i] = dt.Rows.Cast&lt;DataRow&gt;().Select(row =&gt; row.Field&lt;long&gt;(i)).ToArray();
            break;

        default:
            //columns[i] = dt.Rows.Cast&lt;DataRow&gt;().Select(row =&gt; row[i]).ToArray();
            throw new InvalidOperationException(String.Format("Type {0} is not supported", dt.Columns[i].DataType.Name));
    }                
}
</code></pre>