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
Try like this, it's better, safer, uses lazy loading, less code, working, ...:
public IEnumerable 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 catIds = GetIds().ToList();