Search code examples
c#linq-to-sqlcsv

SQL Table to CSV using LINQ


I'm trying to get a table into a comma delimited CSV file. I am currently achieving it like this:

var csv = new StringBuilder("id,Name,Address,City,State\n");
var delimiter = ",";
var newline = "\n";

using (var db = MyDatabase())
{
     var query = from c in db.Customers select c;
     foreach(var q in query)
         csv.Append(q.id).Append(delimiter)
             .Append(q.name).Append(delimiter)
             .Append(q.address).Append(delimiter)
             .Append(q.city).Append(delimiter)
             .Append(q.state).Append(newline);
}

This creates a csv fine. But my question is, is there a more streamlined way I could achieve this without individually specifying each column? In some cases, I'd like to do a select all, but with the tables having lots of columns, it seems a bit clunky.


Solution

  • In order to do this without specifying each property you want to write to the CSV, you would need use reflection. Here is a basic example of how this can be done:

    List<Customer> query = from c in db.Customers select c;
            foreach (var q in query)
            {
                Type type = typeof(Customer);
                PropertyInfo[] properties = type.GetProperties();
                foreach (PropertyInfo property in properties)
                {
                    string value = property.GetValue(type, null) != null
                        ? property.GetValue(type, null).ToString() 
                        : string.Empty; // or whatever you want the default text to be
                    csv.Append(q.id).Append(delimiter);
                }
            }
    

    This will loop through each Customer from the query, and then loop through each property in Customer and write the value. This is assuming that you want each property from Customer to be written to the CSV file. This should at least give you ideas about how to do what you want to accomplish.