2

I have a SqlDataReader reader, where I don't know the data structure in advance, i.e. 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!)?

3
  • use DataTable.AsEnumerable() Commented Aug 8, 2012 at 9:36
  • using it I can query a DataTable object (dt), but I need to query a SqlDataReader object (reader) or something inside it. Commented Aug 8, 2012 at 9:41
  • DataReader has nothing inside it. That's why it is used in a loop. Commented Aug 8, 2012 at 9:42

1 Answer 1

6

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));
Sign up to request clarification or add additional context in comments.

3 Comments

thanks you! just few remarks, I think "var values = ..." should be called before the reader is positioned on any record, i.e. before "while(reader.Read())". Besides, I found out that string.Join requires an array and not a list (it's my fault), so it must be additionally .ToArray() at the end , i.e. "values.Select(v => v.ToString()).ToArray()"
@MaxLi, if you're using FW 3.5 or lower, then, yes - .ToArray() is a requirement.
Nice to know, I'm using FW 3.5. I thought that it's strange that it works only with arrays and not iterables

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.