Wednesday, 8 October 2008

Extension Method for Generic List<T> to Comma Seperated Values

Extension methood can be implemented as follows to convert List of type T values to a comma seperated string. (CSV)


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
///
/// Summary description for MyExtensions
///

public static class MyExtensions
{
public static string ToCSV<T>(this List<T> lst)
{
StringBuilder sb = new StringBuilder();

foreach (T val in lst)
sb.Append("," + val.ToString());

if (sb.Length > 0)
return sb.ToString().Substring(1);
else
return null;

}

}



You will get extension method for any List
Click to enlarge


Usage is as follows

List<short> lst = new List<short> { 1, 5, 7 };

string str = lst.ToCSV<short>();// str will assigned with "1,5,7"


No comments:

Popular Posts