Skip to content

Instantly share code, notes, and snippets.

@kristofclaes
Created October 24, 2012 11:33
Show Gist options
  • Save kristofclaes/3945577 to your computer and use it in GitHub Desktop.
Save kristofclaes/3945577 to your computer and use it in GitHub Desktop.
public class Person
{
public string Name { get; set; }
public string Email { get; set; }
}
var people = new List<Person>
{
new Person { "Troy", "[email protected]" },
new Person { "John", "[email protected]" }
};
string csvString = people.ToCsv();
/*
csvString:
Name;Email
"Troy";"[email protected]"
"John";"[email protected]"
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace System.Collections.Generic
{
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();
string header = string.Join(";", properties.Select(x => x.Name));
csvBuilder.AppendLine(header);
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("\"", "\\\""));
}
if (item is DateTime)
{
return String.Format("\"{0:dd/MM/yyyy}\"", item);
}
double dummy;
if (double.TryParse(item.ToString(), out dummy))
{
return string.Format("{0}", item);
}
return string.Format("\"{0}\"", item);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment