Using Linq to concatenate a list of property of classes
c#, linq
Solution
This will do job for you:
var res = yourList.Select(x => x.Name).Aggregate((current, next) => current + ", " + next);
But, I recommend you to use `String.Join(string separator, IEnumerable<string> values)`:
var res = String.Join(", ", yourList.Select(x => x.Name));
Additional details:
To tell the truth in such situations you can use either `Aggregate` or `String.Join()`. If we test the execution times of both queries, we will see that the second is faster than the first one. But the reason is not the `Aggregate()` function; the problem is that we are concatenating strings in a loop. This will generate lots of intermediate strings, resulting in bad performance. You can use `StringBuilder.Append`, if you want still to use `Aggregate` and increase the performance:
var res = yourList.Select(x => x.Name)
.Aggregate(new StringBuilder(), (current, next) => current.Append(next).Append(", ")).ToString();
`String.Join()` uses a `StringBuilder` internally already and for that reason it will be the best choice.
Problem
I've seen this question (Using LINQ to concatenate strings) which works for strings but what happens if I would like to concatenate a list of string where the string is the property of a class? The method proposed in that question doesn't work (I've tried). Given an array or People I want a string which contains the concatenation of their names. ``` x => person.Name ``` How can I solve this problem?