Join collection of objects into comma-separated string
Posted
by Helen Toomik
on Stack Overflow
See other posts from Stack Overflow
or by Helen Toomik
Published on 2008-12-01T10:45:26Z
Indexed on
2010/04/18
6:23 UTC
Read the original article
Hit count: 413
In many places in our code we have collections of objects, from which we need to create a comma-separated list. The type of collection varies: it may be a DataTable from which we need a certain column, or a List<Customer>, etc.
Now we loop through the collection and use string concatenation, for example:
string text = "";
string separator = "";
foreach (DataRow row in table.Rows)
{
text += separator + row["title"];
separator = ", ";
}
Is there a better pattern for this? Ideally I would like an approach we could reuse by just sending in a function to get the right field/property/column from each object.
© Stack Overflow or respective owner