Going through DataReader twice

I have the following code that does what it should do:

objSQLCommand = New SqlCommand("select * from table1", objSQLConnection) objSQLCommand.Connection.Open() objSQLDataReader = objSQLCommand.ExecuteReader() While objSQLDataReader.Read() objStringBuilder.Append(objSQLDataReader("forename")) objStringBuilder.Append("<br /><br />") objStringBuilder.Append(objSQLDataReader("surname")) objStringBuilder.Append("<br /><br />") End While objSQLDataReader.Close() objSQLCommand.Connection.Close() 

But I need to scroll through objSQLDataReader again. How can I do it?

+4
source share
2 answers

Three options:

  • execute the request twice (readers like this just ahead)
  • buffer the data locally, then process it twice (the "buffer" can be a collection of objects, XML, DataTable (braid), etc.)
  • record both outputs simultaneously ; that is, for each line, write the first format to the first output, then the second format to the second output

I would probably dwell on the latter option, since it does not require buffering or repetition; however, I would move the logic for each method to two different methods.

+10
source

Number the data reader only once and load your data into some instantiated collection (for example, List<MyDataObject> ), which you can reference later to cycle over and over and over.

+3
source

Source: https://habr.com/ru/post/1345896/


All Articles