Many people are looking for a clean way to concatenate the values of a column in a .NET DataSet to a string, so here’s a quick code snippet to do just that:
//concatenate first names of persons found
List<String> listNames = new List<string>();
//get names in a list
foreach (DataRow row in dtPersons.Rows)
listNames.Add(row["name"].ToString());
//concatenate all first names with a comma
String concatNames = String.Join(“,” , listNames.ToArray());
In essence, I’m using a Generic List of Strings (List <String>), then a DataSet.ToArray and a String.Join.
Using a constant declaration for the separator, rather than hard-coding it (as above), is always a good practice.
Note: LINQ has some elegant ways to do this too, but I haven’t used any yet.