I have the following code:
SqlDataReader reader = getAddressQuery.sqlReader;
while (reader.Read())
{
foreach (Object ob in reader)
{
someText.InnerText = someText.InnerText + " " + ob.ToString();
}
}
The code in the foreach loop does not execute. However, I can do this:
SqlDataReader reader = getAddressQuery.sqlReader;
while (reader.Read())
{
someText.InnerText = reader[0].ToString();
}
Which works.
Obviously I could achieve the same result using a regular for loop rather than a foreach loop, but I think the foreach syntax is clearer, so I use it when possible.
What has gone wrong here? Are foreach loops in c# not as flexible as in more high level languages?
Something like the following. Note that
IDataReaderderives fromIDataRecordwhich exposes the members used to process the current row:Or even something like the following, to get an enumeration or list of strongly-typed entity objects from a reader:
UPDATE in response to Caleb Bell’s comment.
I agree
Enumerateis a better name.In fact in my personal “common” library, I’ve now replaced the above by an extension method on
IDataReader:And the caller can get strongly-typed objects using: