简体   繁体   中英

Get the content of a row from sqlDataReader as a list

I have a SqlDataReader reader, where I don't know the data structure in advance, ie the number of columns is unkown. I'd like to put the table in csv file. I retrieve the columns from

System.Data.DataTable dt = reader.GetSchemaTable();

So I have them in dt.Columns() after it. Then, I want to do something like this:

while (reader.Read())
{
    writer.WriteLine(string.Join(";",ListWithRowContent))
}

However, I have it hard to put the content of a row into ListWithRowContent list with something like linq .Select , but "reader" object can't be queried.
Question: how to do it (please no for loop!)?

Assuming, that reader is positioned on any record:

var values = new Object[reader.FieldCount];

reader.GetValues(values);

writer.WriteLine(string.Join(";", values.Select(v => v.ToString())));

or more convenient way (FW 4.0 or higher):

var values = new Object[reader.FieldCount];

reader.GetValues(values);

writer.WriteLine(string.Join(";", values));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM