Thursday, April 17, 2008

Columns to CSV with LINQ

In SQL, I often use the following idiom as a quick-and-dirty method of turning column values into a single - comma separated - value.


DECLARE @csv NVARCHAR(4000)
SELECT @csv = COALESCE(@csv + ', ', '') + CONVERT(NVARCHAR, ColumnName) FROM TableName

I'm now using LINQ more than raw SQL, so here's my version of the equivalent. If you can improve it, please let me know.


string s = null;
var csv = from i in TableName select s = (s == null ? "" : s + ", ") + i;