Search code examples
c#linqentity-framework-5export-to-csv

.Net Entity Framework to CSV


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 DataTable to CSV extraction. 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.

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

Solution

  • Don't use a string to create your file. Try using the StringBuilder class (http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.aspx)

    Strings are immutable objects - that is, once a string is created, it cannot be changed. Every time you change a string (such as concatenate it), you're actually creating a brand new string. Using a string is very inefficient here.

    Instead, create a stringbuilder object:

    StringBuilder builder = new StringBuilder();
    
    builder.Append("my data");
    

    At the end, just call

    builder.ToString();