Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Linq to concatenate a list of property of classes [duplicate]

Tags:

c#

linq

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?

like image 597
Revious Avatar asked Feb 24 '15 18:02

Revious


2 Answers

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.

like image 147
Farhad Jabiyev Avatar answered Sep 18 '22 08:09

Farhad Jabiyev


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

var result = String.Join(",", data.Select(x => x.MyProperty));
like image 21
MarcinJuraszek Avatar answered Sep 22 '22 08:09

MarcinJuraszek