Suppose I have a collection of strings:
\"foo\"
\"bar\"
\"xyz\"
And I would like to generate a comma separated values from the list into someth
As others have said: String.Join
is normally the best way to do this. But what if you have just have an IEnumerable rather than an array? Perhaps you have code to enumerate these as you read them from a file using deferred execution. In this case String.Join isn't quite as nice, because you have to loop over the strings twice — once to create the array and once to join it. In that case, you want something more like this:
public static string ToDelimitedString(this IEnumerable source, string delimiter)
{
string d = "";
var result = new StringBuilder();
foreach( string s in source)
{
result.Append(d).Append(s);
d = delimiter;
}
return result.ToString();
}
This will perform almost as well as String.Join, and works in the more general case. Then, given a string array or any other IEnumerable you can call it like this:
string finalStr = MyStrings.ToDelimitedString(",");