I have the following extension method that takes a List and converts it to a comma separated string:
static public string ToCsv(this List<string> lst)
{
const string SEPARATOR = ", ";
string csv = string.Empty;
foreach (var item in lst)
csv += item + SEPARATOR;
// remove the trailing separator
if (csv.Length > 0)
csv = csv.Remove(csv.Length - SEPARATOR.Length);
return csv;
}
I want to do something analogous but apply it to a List (instead of List of String) , however, the compiler can’t resolve for T:
static public string ToCsv(this List<T> lst)
{
const string SEPARATOR = ", ";
string csv = string.Empty;
foreach (var item in lst)
csv += item.ToString() + SEPARATOR;
// remove the trailing separator
if (csv.Length > 0)
csv = csv.Remove(csv.Length - SEPARATOR.Length);
return csv;
}
What am I missing?
First, the method declaration should be:
Note that the method must be parameterized; this is the
<T>after the name of the method.Second, don’t reinvent the wheel. Just use
String.Join:Note that I’ve gone hog wild and generalized the method further by accepting an
IEnumerable<T>instead of aList<T>.In .NET 4.0 you will be able to say:
That is, we do not require to convert the result of
source.Select(x => x.ToString())to an array.Finally, for an interesting blog post on this topic, see Eric Lippert’s post Comma Quibbling.