tags:

views:

288

answers:

2
 class Person
 {
 public string FirstName { get; set; }
 public string LastName { get; set; }
 }

 List<Person> theList = populate it with a list of Person objects

How can I get a string which contains all the FirstName of the objects in the list separated by a comma. Eg: John,Peter,Jack

A basic solution would be to iterate through each object but I'm sure there is a one-line solution.

Thanks.

+6  A: 
string.Join(",", theList.ConvertAll(person => person.FirstName).ToArray());

Breaking it down into component parts:

List<T>.ConvertAll converts a List<T> to another type - in this case a List<string>.

ToArray() converts the List<string> to a string[].

string.Join() writes an array of strings (the second parameter) as a single string, separated by the first parameter.

Rex M
+3  A: 

You could also use a query extension method

string output = theList.Select(p => p.FirstName).Aggregate((progress, next) => progress + ", " + next);

This will avoid having to create an array.

Adam Robinson