tags:

views:

678

answers:

2

Is there an easier way to achieve the following?

var obj = from row in table.AsEnumerable()
          select row["DOUBLEVALUE"];

double[] a = Array.ConvertAll<object, double>(obj.ToArray(), o => (double)o);

I'm extracting a column from a DataTable and storing the column in an array of doubles.

Assume that table is a DataTable containing a column called "DOUBLEVALUE" of type typeof(Double).

+1  A: 
double[] a = (from row in table.AsEnumerable()
              select Convert.ToDouble( row["DOUBLEVALUE"] )).ToArray();

If you have rows that may have null values for that column, add where row["DOUBLEVALUE"] != null before the select.

tvanfosson
+2  A: 
var obj = (from row in table.AsEnumerable()
      select row.Field<double>("DOUBLEVALUE")).ToArray();

The .ToArray() bit is optional, of course; without the ToArray(), you'll get an enumerable sequence of doubles instead of an array - it depends whether you need to read it once or twice. If you have nulls in the data, use <double?> instead.

(note that this needs a reference to System.Data.DataSetExtensions.dll, and a "using System.Data;" statement - this brings the .Field<T>(...) extension methods into play)

Marc Gravell