Linq To CSV

LinqToCSV Class

namespace FooFoo
{
    public static class LinqToCSV
    {
        public static string ToCsv<T>(this IEnumerable<T> items)
            where T : class
        {
            var csvBuilder = new StringBuilder();
            var properties = typeof(T).GetProperties();
            foreach (T item in items)
            {
                string line = string.Join(",",properties.Select(p => p.GetValue(item, null).ToCsvValue()).ToArray());
                csvBuilder.AppendLine(line);
            }
            return csvBuilder.ToString();
        }
 
        private static string ToCsvValue<T>(this T item)
        {
            if(item == null) return "\"\"";
 
            if (item is string)
            {
                return string.Format("\"{0}\"", item.ToString().Replace("\"", "\\\""));
            }
            double dummy;
            if (double.TryParse(item.ToString(), out dummy))
            {
                return string.Format("{0}", item);
            }
            return string.Format("\"{0}\"", item);
        }
    }
}

Example of usage:

public string Get()
{
    var db = new Db();
    var data = db.Database.SqlQuery<SQLResult>(Query()).ToList();
    var csv =  data.ToCsv();

    var path = HttpContext.Current.Server.MapPath(@"~/Content/data.csv");

    // Create a file to write to.
    using (StreamWriter sw = File.CreateText(path))
    {
        sw.Write(csv);
        sw.Flush();
    }
    return "File Updated";
}

 

Source : https://www.hanselman.com/blog/BackToBasicsKeepItSimpleAndDevelopYourSenseOfSmellFromLinqToCSV.aspx

Author:

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.