• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 616
  • Last Modified:

C# Datatable to double[]

What is the easiest way to convert a column of data from a datatable to a double[]?  I am trying to populate a componentone chart and can't get the binding to work right so I figured I would try the brute force method and set the chart to double[] and be done with it.  I am trying to go to a List<double> and then from the list to double[] but I get an error when trying to compile the list that
"Error      1      The as operator must be used with a reference type or nullable type ('double' is a non-nullable value type)"

I am open to cleaner ways to do this.
thanks
foreach (DataRow myRow in sim1.Tables["Data"].Rows)
            {
 
                xdata.Add(myRow["Count"] as double);
            }

Open in new window

0
perrytaylor
Asked:
perrytaylor
  • 2
1 Solution
 
Todd GerbertIT ConsultantCommented:
foreach (DataRow myRow in sim1.Tables["Data"].Rows)
    xdata.Add((double)myRow["Count"]);
0
 
GuitarRichCommented:
couple of ways:
 

foreach (DataRow myRow in sim1.Tables["Data"].Rows)
{
    // Check the data for nulls and default to zero if it is null
    xdata.Add( myRow["Count"] == null ? 0 : (double)myRow["count"] );
 
OR
   // use tryparse:
   double tmp = 0;
   double.TryParse(myRow["Count"], out tmp);
   xdata.Add(tmp);
 
}

Open in new window

0
 
HarryNSCommented:
List<double> lstValues = new List<double>(dt.Rows.Count);
            foreach (DataRow dr in dt.Rows)
            {
                lstValues.Add(double.Parse(dr["Column Name"].ToString()));
            }
0
 
Todd GerbertIT ConsultantCommented:
GuitarRich raises a good point - unless you know there won't be any null values in your DataSet you should check it first to avoid a runtime Exception.
0

Featured Post

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now