简体   繁体   English

从sqlDataReader获取行的内容作为列表

[英]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. 我有一个SqlDataReader阅读器,我事先不知道数据结构,即列数未知。 I'd like to put the table in csv file. 我想将表格放在csv文件中。 I retrieve the columns from 我从中检索列

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

So I have them in dt.Columns() after it. 所以我在dt.Columns()之后有它们。 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. 但是,我很难用linq .Select之类的内容将行的内容放入ListWithRowContent列表中,但是无法查询“ reader”对象。
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): 或更便捷的方式(FW 4.0或更高版本):

var values = new Object[reader.FieldCount];

reader.GetValues(values);

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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