Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join collection of objects into comma-separated string

Tags:

c#

.net

.net-3.5

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.

like image 902
Helen Toomik Avatar asked Dec 01 '08 10:12

Helen Toomik


People also ask

How do you join a List of strings with a comma?

In Java, we can use String. join(",", list) to join a List String with commas.

How can use comma-separated value in C#?

string s = "a,b, b, c"; string[] values = s. Split(','). Select(sValue => sValue.

How do you add comma-separated Values in an ArrayList in Java?

List<String> items = Arrays. asList(commaSeparated. split(",")); That should work for you.


1 Answers

string.Join(", ", Array.ConvertAll(somelist.ToArray(), i => i.ToString())) 
like image 93
leppie Avatar answered Sep 23 '22 13:09

leppie