views:

37

answers:

4

Hi,
I need to iterate twice through a DataReader. Is there a way to do this without using DataSets and without running the query twice? I'm using C#, by the way.
Thanks

+2  A: 

The short answer is no, you run through the enumeration for the result sets and then you're done. What should probably be done is to dump the results to some kind of simplified raw results that you can iterate over as much as you want (avoiding the overhead of the DataSet).

If you take a peek at MSDN, it notes that the SqlDataReader is "forward only" which would suggest again that this isn't possible.

Will Charczuk
I know that it is forward only... I just thought there might be some way to get around it, but thanks!
Pascal
A: 

The IDataReader spec does not allow the list to be reset, however check the specific implementation also implements IEnumerator or has a GetEnumerator() function there is a Reset command as part of that interface.

Scott Chamberlain
If the Reset method works on that class and doesn't just throw a `NotImplementedException` it will most likely requery the database.
Matthew Whited
+1  A: 

It is possbile but not so simple, because data reader mutates on each Read() call. So you need to store previous values somewhere to access it next time. Using data set is not so bad idea here.

STO
+2  A: 

Its a forward-only reader, you cannot go back. Your best bet is that instead of iterating twice the data reader, do both operations you want to do in one iteration.

You can cache the results yourself but that's like destroying the purpose of the DataReader, so if you need to have the data handy many times, you have to choose another way to access it.

Francisco Soto