2

What is a good way to save a particular column of a DataReader into a comma separated string?

For instance here is what I have now:

     StringBuilder sb = new StringBuilder(); 
     Database db = DatabaseFactory.CreateDatabase();
     using(DbCommand dbcmd = mydb.GetStoredProcCommand("ProcStoredProc")) //No Parameters
     {
       IDataReader dr = db.ExecuteReader(sqlcmd)
       while(dr.Read())
       {
                 sb.AppendFormat("{0},",dr["CODE"]);
       }
       dr.Dispose();
     }

     // skipped code to remove the last comma. 
     string CSVString = sb.ToString();

The DataReader will not contain more than 10 rows in this example.

Thank you.

FMFF
  • 1,652
  • 4
  • 32
  • 62
  • 6
    What's wrong with what you have now? – Chris Shain Jan 23 '12 at 19:30
  • Thank you @Chris Shain: It appears to be too many steps just to get 10 rows; Was wondering if there is an elegant approach to this. Thank you. – FMFF Jan 23 '12 at 19:32
  • 2
    Looks fine to me. Most of what you have is around database plumbing- syntactic sugar can make that shorter, but all of the work it does is still going to happen. – Chris Shain Jan 23 '12 at 19:35
  • Would using DataSet/DataTable result in fewer lines of code? – FMFF Jan 23 '12 at 19:38
  • 1
    Unlikely, and it would be slower. – Chris Shain Jan 23 '12 at 19:38
  • Code looks fine to me. I would refactor the database connection code that can be reused for execute reader functionality. We could also use dataadapter with dataset where we can enumerate rows using linq. That way we could avoild while loop. Still it is only an elegant way. Lines of code that need to be executed are same. – Amzath Jan 23 '12 at 19:42

1 Answers1

4

Some syntactic sugar could be:

using(var dbcmd = mydb.GetStoredProcCommand("ProcStoredProc"))
using(var dr = db.ExecuteReader(sqlcmd))
  var result = string.Join(",", reader.AsEnumerable().Select (r => r["Code"]));

Helper function

public static IEnumerable<IDataRecord> AsEnumerable(this IDataReader reader)
{
    while (reader.Read())
        yield return reader;
}
Magnus
  • 45,362
  • 8
  • 80
  • 118