Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CSHARP

C# ToCsv Extension Method

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);
		}
Source by www.extensionmethod.net #
 
PREVIOUS NEXT
Tagged: #ToCsv #Extension #Method
ADD COMMENT
Topic
Name
4+5 =