Fill an array (or arraylist) from SqlDataReader

前端 未结 7 525
滥情空心
滥情空心 2020-12-01 05:36

Is there a way to fill an array via a SqlDataReader (or any other C# ADO.NET object) without looping through all the items? I have a query that is returning a single column

相关标签:
7条回答
  • 2020-12-01 06:14

    No, since SqlDataReader is a forward-only read-only stream of rows from a SQL Server database, the stream of rows will be looped through whether explicitly in your code or hidden in a framework implementation (such as DataTable's Load method).

    It sounds like using a generic list and then returning the list as an array would be a good option. For example,

    List<int> list = new List<int>();
    
    using (SqlDataReader reader = cmd.ExecuteReader())
    {
        while (reader.Read())
        {
             list.Add(reader.GetInt32(0));
        }    
    }
    return list.ToArray();
    

    In response to your comment, calling ToArray() may be overhead, it depends. Do you need an array of objects to work with or would a generic collection (such as List<T> or ReadOnlyCollection<T>) be more useful?

    0 讨论(0)
提交回复
热议问题