Thursday, September 3, 2009

Comma-separated Lists

One needs to convert a list of objects to comma-separated list of values sometimes. I often see StringBuilder used with some sort of loop. The most intellectual challenge is not to write comma after the last item; either there is some conditional expression in the loop step or some post processing is included to remove the last comma. Usually the result is consisting of several lines of code, perhaps too many for the purpose.

Users enthusiastic about Linq tend to involve Enumerable.Aggregate. Still String.Join may be the most straightforward method many times.