title: .Net Entity Framework to CSV
body: <p>I'm using the latest Entity Framework with DBContext. I have a result set that I want to convert to comma separated values. I've done something similar with DataTables in VB <a href="http://consciouscipher.wordpress.com/2012/07/09/166/" rel="nofollow">DataTable to CSV extraction</a>. I've got the QuoteName method working. I've also get a derivative of the GetCSV method working using a foreach. The problem is that it is a lot slower than the comparable code for a DataTable. So I'm hoping someone will have some suggestions.</p>
  
  <pre><code>    public static string GetCSV(this IQueryable entity)
      {
          if (entity == null)
          {
              throw new ArgumentNullException("entity");
          }
          Type T = entity.ElementType;
          var props = T.GetProperties(BindingFlags.Public | BindingFlags.Instance);
          string s = string.Empty;
          int iCols = props.Count();
  
          try
          {
              s += string.Join(",", (from int ii in Enumerable.Range(0, iCols)
                                     select props[ii].Name.QuoteName("[]")).ToArray());
              s += Environment.NewLine;
              foreach (var dr in entity)
              {
                  s += string.Join(",", (from int ii in Enumerable.Range(0, iCols)
                                         select
                                             props[ii].GetValue(dr)
                                                      .ToString()
                                                      .QuoteName("\"\"", ",")).ToArray());
                  s += Environment.NewLine;
              }
              s = s.TrimEnd(new char[] { (char)0x0A, (char)0x0D });
          }
          catch (Exception)
          {
  
              throw;
          }
          return s;
      }
  </code></pre>