0

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.

1
  • Dont forget to mark answer as accpeted if you got the info you want... Commented Apr 11, 2012 at 8:17

3 Answers 3

7

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[], ...).

Sign up to request clarification or add additional context in comments.

Comments

4

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());
        }

Comments

0
DataTable mydt = new DataTable();
ArrayList aLrows = new ArrayList();

foreach (DataRow dataRow in mydt.Rows)
{
  aLrows.Add(string.Join(";", dataRow.ItemArray.Select(item => item.ToString)));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.