Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

list

 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.

like image 792
Anthony Avatar asked Aug 25 '09 18:08

Anthony


2 Answers

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.

like image 126
Rex M Avatar answered Nov 01 '22 14:11

Rex M


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.

like image 6
Adam Robinson Avatar answered Nov 01 '22 13:11

Adam Robinson