20 July 2011

Concatenating a long set of objects in a string with a separator

It still amazes me when I see people concatenating a long set of repetitive strings with a StringBuilder, adding a separator to each string it, and then remove the last separator – or doing some complex if-statement comparing a count or index to prevent a trailing separator or something.

This is a very simple trick I use a lot of times when I need, for instance, to change a list of points into it’s Well Known Text (WKT) representation. So let’s assume we have a variable points of IList<System.Windows.Point>, that I want to convert to a list of coordinates that fit in WKT string. That is: X and Y separated by a space, and coordinates separated by a comma. I can do that with this simple statement that would have been a one-liner if it had not been for lack of space ;-) :

var pointString = 
  string.Join(", ",
    points.Select(p => 
      string.Format(CultureInfo.InvariantCulture, "{0} {1}", p.X, p.Y)));

If I had points X=10, Y=15, X=20, Y=25 and X=30 ,Y=40 this would nicely translate to

10 15,20 25,30 40

That's all. No loops, no truncating trailing comma’s: just a Select and a Join

No comments: