Fill an array (or arraylist) from SqlDataReader

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

    The orignial OP asked for Array, ArrayList or List. You can return Array as well. Just call the .ToArray() method and assign it to a previously declared array. Arrays are very fast when it comes to enumerating each element. Much faster than a List if the list has more than 1000 elements. You can return to Array, List, or Dictionary.

    ids_array = (from IDataRecord r in idReader 
    select (string)r["ID"]).ToArray();  
    

    Additionally, if you are using a lookup of keys for example, you might consider creating a HashSet object with has excellent lookup performance if you are simply checking one list against another to determine if an elements key exists in the HashSet object. example:

     HashSet hs = new HashSet( 
    (from IDataRecord r in idReader select (string)r["ID"]).AsEnumerable() );
    

提交回复
热议问题