Fill an array (or arraylist) from SqlDataReader

前端 未结 7 563
滥情空心
滥情空心 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:04

    It is possible. In .NET 2.0+, SqlDataReader inherits from DbDataReader, which implements IEnumerable (non-generic one). This means that you can use LINQ:

    List list = (from IDataRecord r in dataReader
                         select (string)r["FieldName"]
                        ).ToList();
    

    That said, the loop is still there, it's just hidden in Enumerable.Select, rather than being explicit in your code.

提交回复
热议问题