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?
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.
If it's LINQ to Objects, you should use String.Join
:
var result = String.Join(",", data.Select(x => x.MyProperty));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With