How to join a generic list of objects on a specific property

.net, c#, list

Solution

Update (as of .NET 4) `string.Join` now has an overload which takes an `IEnumerable<string>` - yay!

string.Join(",", theList.Select(p => p.FirstName));

For .NET versions below 4.0 (older):

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.

Problem

``` 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.

Original source