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.