Search code examples
c#csvado.netdatareaderenterprise-library-5

Comma Separated String from a DataReader Column


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.


Solution

  • 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;
    }