Found a simple way of doing a separated list, similar to PHP's implode function. The code expects the variable "Values" to be of an IEnumerable type, which includes arrays, lists, etc. Very useful for doing comma delimited lists.
Instead of doing:
string commaList = "";
foreach (string value in Values)
{
commaList = commaList + value;
commaList = commaList + ", ";
}
commaList = commaList.Substring(0, commaList .Length - 2);
It's easier (and faster) to do (.Net 4.0):
string commaList=string.Join(", ", Values);
.Net 3/3.5:
string commaList=string.Join(", ", Values.ToArray());
.Net 2.0:
string commaList=string.Join(", ",new List<string>(Values).ToArray());
Of course the join function allows any separator to be used, not just ", ".
And, according to this post, string.Join is faster than StringBuilder in this particular case.
No comments:
Post a Comment