ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

ToCsv

Returns a string that represent a csv representation of the referenced T in the IEnumerable<T>. You can also generate a columns header (the first row) with the name of the serialized properties. You can specify the name of the properties to include in the csv file. If you don't specify anything it will includes all the public properties.

Source

public static string ToCsv<T>(this IEnumerable<T> instance, bool includeColumnHeader, string[] properties)
		{
			if (instance == null)
				return null;

			var csv = new StringBuilder();

			if (includeColumnHeader)
			{
				var header = new StringBuilder();
				foreach (var property in properties)
					header.AppendFormat("{0},", property);

				csv.AppendLine(header.ToString(0, header.Length - 1));
			}

			foreach (var item in instance)
			{
				var row = new StringBuilder();

				foreach (var property in properties)
					row.AppendFormat("{0},", item.GetPropertyValue<object>(property));

				csv.AppendLine(row.ToString(0, row.Length - 1));
			}

			return csv.ToString();
		}

		public static string ToCsv<T>(this IEnumerable<T> instance, bool includeColumnHeader)
		{
			if (instance == null)
				return null;

			var properties = (from p in typeof(T).GetProperties()
							  select p.Name).ToArray();

			return ToCsv(instance, includeColumnHeader, properties);
		}

Example

var list = new List<Employee>();
list.Add(new List(){FirstName = "Jon", LastName = "Doe"});
list.Add(new List(){FirstName = "Scott", LastName = "Gu"});

string csv = list.ToCsv(true);

or

string csv = list.ToCsv(true, new[] {"FirstName", "LastName"});

Author: Lorenzo Melato

Submitted on: 16 mrt. 2011

Language: C#

Type: System.Collection.Generic.IEnumerable<T>

Views: 6552