How to generate List<String> from SQL query?

Viewed 121621

If I have a DbCommand defined to execute something like:

SELECT Column1 FROM Table1

What is the best way to generate a List<String> of the returned records?

No Linq etc. as I am using VS2005.

6 Answers

Or a nested List (okay, the OP was for a single column and this is for multiple columns..):

        //Base list is a list of fields, ie a data record
        //Enclosing list is then a list of those records, ie the Result set
        List<List<String>> ResultSet = new List<List<String>>();

        using (SqlConnection connection =
            new SqlConnection(connectionString))
        {
            // Create the Command and Parameter objects.
            SqlCommand command = new SqlCommand(qString, connection);

            // Create and execute the DataReader..
            connection.Open();
            SqlDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                var rec = new List<string>();
                for (int i = 0; i <= reader.FieldCount-1; i++) //The mathematical formula for reading the next fields must be <=
                {                      
                    rec.Add(reader.GetString(i));
                }
                ResultSet.Add(rec);

            }
        }

This version has the same purpose of @Dave Martin but it's cleaner, getting all column, and easy to manipulate the data if you wan't to put it on Email, View, etc.

List<string> ResultSet = new List<string>();
using (SqlConnection connection = DBUtils.GetDBConnection())
{
    connection.Open();
    string query = "SELECT * FROM DATABASE";
    using (SqlCommand command = new SqlCommand(query, connection))
    {
        using (SqlDataReader reader = command.ExecuteReader())
        {
             while (reader.Read())
             {
                  var rec = new List<string>();
                  for (int i = 0; i <= reader.FieldCount - 1; i++)
                  {
                       rec.Add(reader.GetString(i));
                  }
                  string combined = string.Join("|", rec);
                  ResultSet.Add(combined);
             }
        }
    }
}
Related