jason
jason

Reputation: 241651

Extract column of doubles from a DataTable

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).

Upvotes: 2

Views: 3634

Answers (2)

Marc Gravell
Marc Gravell

Reputation: 1062975

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)

Upvotes: 2

tvanfosson
tvanfosson

Reputation: 532505

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.

Upvotes: 2

Related Questions