0

I need to populate a generic List of string with the result set of a single-column query. I've got this code:

private List<String> _mammalsList; 
. . .
private void LoadMammalStringList()
{
    _mammalsList = new List<string>();
    using (SqlConnection con = new SqlConnection(PlatypusUtils.DuckbillConnStr))
    {
        using (SqlCommand cmd = new SqlCommand(PlatypusUtils.SelectMammalIdQuery, con))
        {
            cmd.CommandType = CommandType.Text;
            using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
            {
                DataTable dt = new DataTable();
                sda.Fill(dt);
                // Now that the data is in dt, how can I pull it out of there and put it into the List<String>?
            }
        }
    }
}

...but don't know just how to access the data set returned. How can I do that?

B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862
  • 2
    See here for similar question: http://stackoverflow.com/questions/15129770/one-columned-datatable-to-liststring – momar Dec 11 '15 at 22:47

1 Answers1

0

Replace the "what now?" comment with this code:

foreach (DataRow row in dt.Rows)
{
    _mammalsList.Add(row.ItemArray[0].ToString());
}

In context:

private void LoadMammalsStringList()
{
    _mammalsList = new List<string>();
    using (SqlConnection con = new SqlConnection(PlatypusUtils.DuckbillConnStr))
    {
        using (SqlCommand cmd = new SqlCommand(PlatypusUtils.SelectMammalIdQuery, con))
        {
            cmd.CommandType = CommandType.Text;
            using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
            {
                DataTable dt = new DataTable();
                sda.Fill(dt);
                foreach (DataRow row in dt.Rows)
                {
                    _mammalsList.Add(row.ItemArray[0].ToString());
                }
            }
        }
    }
}

UPDATE

As alluded to by Momar, this also works:

//foreach (DataRow row in dt.Rows)
//{
//    _membersList.Add(row.ItemArray[0].ToString());
//}
_mammalsList = dt.AsEnumerable()
   .Select(r => r.Field<string>("mammalId"))
   .ToList();

Which approach is preferable, I don't know.

B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862