ToCSV
An extension method that produce a comman separated values of string out of an IEnumerable<T>. This would be useful if you want to automatically generate a CSV out of integer, string, or any other primative data type collection or array. I provided 2 overloads of this method. One of them accepts a separator and the other uses comma "," as default separator. Also I am using another shortcut extension method for foreach loop.
Source
public static void Each<T>(this IEnumerable<T> enumerable, Action<T> action)
{
foreach (T item in enumerable)
{
action(item);
}
}
public static string ToCSV<T>(this IEnumerable<T> instance, char separator)
{
StringBuilder csv;
if (instance != null)
{
csv = new StringBuilder();
instance.Each(value => csv.AppendFormat("{0}{1}", value, separator));
return csv.ToString(0, csv.Length - 1);
}
return null;
}
public static string ToCSV<T>(this IEnumerable<T> instance)
{
StringBuilder csv;
if (instance != null)
{
csv = new StringBuilder();
instance.Each(v => csv.AppendFormat("{0},", v));
return csv.ToString(0, csv.Length - 1);
}
return null;
}
Example
[TestMethod]
public void ToCSV_Should_Return_Correct_Comma_Separated_Values()
{
var values = new[] {1, 2, 3, 4, 5};
string csv = values.ToCSV();
Assert.AreEqual("1,2,3,4,5",csv);
}
[TestMethod]
public void ToCSV_Should_Return_Correct_Comma_Separated_Values_Using_Specified_Separator()
{
var values = new[] { 1, 2, 3, 4, 5 };
string csv = values.ToCSV(';');
Assert.AreEqual("1;2;3;4;5", csv);
}
Author: Muhammad Mosa
Submitted on: 16 dec. 2009
Language: C#
Type: System.Collections.Generic.IEnumerable<T>
Views: 12685