c# - Fill generic list from SqlDataReader

前端 未结 5 1865
轮回少年
轮回少年 2021-02-14 02:23

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

5条回答
  •  日久生厌
    2021-02-14 02:54

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

提交回复
热议问题