Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# - Fill generic list from SqlDataReader

How can I add values that a SqlDataReader returns to a generic List? I have a method where I use SqlDataReader to get CategoryID from a Category table. I would like to add all the CategoryID a generic List.

This dose not work because it returns only one categoryID and that is the last one. I want to add all the categoryID to the list and then return them.

How do I do that?

SqlConnection connection = null;
SqlDataReader reader = null;
SqlCommand cmd = null;

try
{
    connection = new SqlConnection(connectionString);
    cmd = new SqlCommand("select CategoryID from Categories", connection );

    connection.Open();

    List<int> catID = new List<int>();
    dr = cmd.ExecuteReader();
    while (dr.Read())
    {
        catID.Add(Convert.ToInt32(dr["CategoryID"].ToString()));
    }
}
finally
{
    if (connection  != null)
        connection.Close();
}
return catID;
like image 761
Erik Avatar asked Apr 10 '11 16:04

Erik


2 Answers

Try like this, it's better, safer, uses lazy loading, less code, working, ...:

public IEnumerable<int> GetIds()
{
    using (var connection = new SqlConnection(connectionString))
    using (var cmd = connection.CreateCommand())
    {
        connection.Open();
        cmd.CommandText = "select CategoryID from Categories";
        using (var reader = cmd.ExecuteReader())
        {
            while (reader.Read())
            {
                yield return reader.GetInt32(reader.GetOrdinal("CategoryID"));
            }
        }
    }
}

and then:

List<int> catIds = GetIds().ToList();
like image 50
Darin Dimitrov Avatar answered Oct 24 '22 06:10

Darin Dimitrov


Your current code should work, assuming catID is really declared before the try block, otherwise this won't compile.

like image 3
BrokenGlass Avatar answered Oct 24 '22 08:10

BrokenGlass