[c#] How to generate List<String> from SQL query?

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.

This question is related to c# sql list visual-studio-2005 dbcommand

The answer is


Where the data returned is a string; you could cast to a different data type:

(from DataRow row in dataTable.Rows select row["columnName"].ToString()).ToList();

If you would like to query all columns

List<Users> list_users = new List<Users>();
MySqlConnection cn = new MySqlConnection("connection");
MySqlCommand cm = new MySqlCommand("select * from users",cn);
try
{
    cn.Open();
    MySqlDataReader dr = cm.ExecuteReader();
    while (dr.Read())
    {
        list_users.Add(new Users(dr));
    }
}
catch { /* error */ }
finally { cn.Close(); }

The User's constructor would do all the "dr.GetString(i)"


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

            }
        }

I think this is what you're looking for.

List<String> columnData = new List<String>();

using(SqlConnection connection = new SqlConnection("conn_string"))
{
    connection.Open();
    string query = "SELECT Column1 FROM Table1";
    using(SqlCommand command = new SqlCommand(query, connection))
    {
        using (SqlDataReader reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                columnData.Add(reader.GetString(0));
            }         
        }
    }
}

Not tested, but this should work fine.


Loop through the Items and Add to the Collection. You can use the Add method

List<string>items=new List<string>();
using (var con= new SqlConnection("yourConnectionStringHere")
{
    string qry="SELECT Column1 FROM Table1";
    var cmd= new SqlCommand(qry, con);
    cmd.CommandType = CommandType.Text;
    con.Open();
    using (SqlDataReader objReader = cmd.ExecuteReader())
    {
        if (objReader.HasRows)
        {              
            while (objReader.Read())
            {
              //I would also check for DB.Null here before reading the value.
               string item= objReader.GetString(objReader.GetOrdinal("Column1"));
               items.Add(item);                  
            }
        }
    }
}

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to sql

Passing multiple values for same variable in stored procedure SQL permissions for roles Generic XSLT Search and Replace template Access And/Or exclusions Pyspark: Filter dataframe based on multiple conditions Subtracting 1 day from a timestamp date PYODBC--Data source name not found and no default driver specified select rows in sql with latest date for each ID repeated multiple times ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database

Examples related to list

Convert List to Pandas Dataframe Column Python find elements in one list that are not in the other Sorting a list with stream.sorted() in Java Python Loop: List Index Out of Range How to combine two lists in R How do I multiply each element in a list by a number? Save a list to a .txt file The most efficient way to remove first N elements in a list? TypeError: list indices must be integers or slices, not str Parse JSON String into List<string>

Examples related to visual-studio-2005

How to generate List<String> from SQL query? Unable to copy file - access to the path is denied How do I print to the debug output window in a Win32 app? How to debug a referenced dll (having pdb) What is the difference between Release and Debug modes in Visual Studio? The name 'controlname' does not exist in the current context How do I programmatically get the GUID of an application in .NET 2.0 Cannot find Dumpbin.exe How to fix "Referenced assembly does not have a strong name" error? ERROR : [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

Examples related to dbcommand

How to generate List<String> from SQL query?