DataReader cursor rewind

2019-02-25 01:39发布

问题:

How do I can rewind a cursor of a DataReader to the beginning?

With one DataReader result I need to run two while loop, but those have to be from beginning. They are two iterations in one result set running a query once.

Example:

dr = command.ExecuteReader(cmd);

while (dr.Read()) { 
    // do some...
}

// rewind cursor here

while (dr.Read()) {
    // do another things...
}

I've looked into the DataReader docs and I've found nothing, so if it can't be possible with DataReader, I may change the class for one that fits this purpose.

回答1:

You cannot (unless you execute the command again): it is a one-way stream. If you want to see the data more than once you'll have to buffer it in memory yourself, for example in a List<T> (for some T), or (yeuch) as a DataTable.