C# – converting an IEnumerable item’s single property to a CSV

I recently had to extract some items from an IList and pass their Guid identifiers to a legacy SQL Server stored procedure that required a list of comma-separated values.

Rather than loop round the list, appending items to a string with a comma at the end, then stripping the last comma off, or adding the chosen property to a IList, converting it to an array and then String.Join-ing that array, I came up with the following:

string divisionsCSV = String.Join(",", ((List)divisions).ConvertAll(d => d.DivisionID.ToString("b")).ToArray());

(There’s a casting of divisions to an List<IDivisionView> because a) divisions is an IList and b) ConvertAll is on the concrete implementation of IList)

I'm using ConvertAll to, er, convert a single property of every item in the list, in this case the Guid identifier of the division to a string. Incientally, I'm keeping the Guid parentheses thanks to the "b" parameter of the ToString call. The ToArray call then stuffs it all into an array ready for the String.Join call.

Any thoughts, comments or improvements?

About mike

A nice guy, web developer using ASP.Net, martial arts fan and practitioner (when not crippled), film buff, husband and father :-)