I want to store the result of select query in an array in C#. Please tell me how to get datatable values and store in an array. My select query result contains n rows and only one column.
3 Answers
Replace type with the data type of your single column (e.g. int, string, ...) and myField with the name of your single column.
var myArray = (from row in myDataTable.AsEnumerable()
select row.Field<type>("myField")).ToArray();
Using the magic of C#'s generics and type inference, your array will automatically have the correct data type (e.g. int[], string[], ...).
Comments
Try something like this
private void getData()
{
SqlCeConnection conn = new SqlCeConnection("data source='c:\\northwind.sdf'; mode=Exclusive;");
SqlCeDataAdapter da = new SqlCeDataAdapter("Select [Unit Price] from Products", conn);
DataTable dtSource = new DataTable();
da.Fill(dtSource);
DataRow[] dr = new DataRow[dtSource.Rows.Count];
dtSource.Rows.CopyTo(dr, 0);
double[] dblPrice= Array.ConvertAll(dr, new Converter<DataRow , Double>(DataRowToDouble));
}
public static double DataRowToDouble(DataRow dr)
{
return Convert.ToDouble(dr["Unit Price"].ToString());
}