Reputation: 354
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.
Upvotes: 0
Views: 9352
Reputation: 7525
DataTable mydt = new DataTable();
ArrayList aLrows = new ArrayList();
foreach (DataRow dataRow in mydt.Rows)
{
aLrows.Add(string.Join(";", dataRow.ItemArray.Select(item => item.ToString)));
}
Upvotes: 0
Reputation: 172360
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[]
, ...).
Upvotes: 7
Reputation: 176936
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());
}
Upvotes: 4