11

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?

Community
  • 1
  • 1
Revious
  • 7,816
  • 31
  • 98
  • 147
  • use `.Select(x => x.Name)` or `string.Join`. – Daniel A. White Feb 24 '15 at 18:02
  • 2
    Do it the same way the question you linked to does it, current and next are `Person` objects instead of strings. – Craig W. Feb 24 '15 at 18:03
  • @CraigW.: it doesn't work I've already tried. I would ban whoever downvoted without any effort. – Revious Feb 25 '15 at 09:56
  • @Daniel A. White, Servy: i would ban you both for lack of effort. The question is not duplicated. As you can see from the proposed solution. – Revious Feb 25 '15 at 09:59
  • @Revious, when asking for help threatening bans isn't the best way to endear yourself to people. You might consider providing some detail beyond "doesn't work (I've tried)" because without knowing what code you actually wrote and what errors you got it makes it a little difficult to diagnose a problem and propose solutions. – Craig W. Feb 25 '15 at 13:16

2 Answers2

24

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.

Nick
  • 138,499
  • 22
  • 57
  • 95
Farhad Jabiyev
  • 26,014
  • 8
  • 72
  • 98
6

If it's LINQ to Objects, you should use String.Join:

var result = String.Join(",", data.Select(x => x.MyProperty));
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263