-1

I have a list of strings called people. I want to combine these and separate them with commas and store them in a variable called totalPeopleNames. This is what I have but it's not working:

string totalPeopleNames = null;

foreach(var person in people)
{
    Enumerable.Concat(totalPeopleNames, ", " + person.Person.FullName);
}
DannyD
  • 2,732
  • 16
  • 51
  • 73
  • possible duplicate of [Create comma separated strings C#?](http://stackoverflow.com/questions/4884050/create-comma-separated-strings-c) or http://stackoverflow.com/questions/330493/join-collection-of-objects-into-comma-separated-string or http://stackoverflow.com/questions/2917571/linq-how-do-i-concatenate-a-list-of-integers-into-comma-delimited-string – Tim Schmelter Mar 28 '13 at 23:10

4 Answers4

9
var totalPeopleNames = String.Join(", ",people.Select(p=>p.Person.FullName))
I4V
  • 34,891
  • 6
  • 67
  • 79
1

The easiest way is to use String.Join

var names = String.Join(", ", people.Select(p => p.Person.FullName));
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
0

One possible solution:

string totalPeopleNames = "";

foreach(var person in people)
{
    totalPeopleNames += totalPeopleNames + ", " + person.Person.FullName;
}

BETTER:

Look at C# "Text.StringBuilder":

paulsm4
  • 114,292
  • 17
  • 138
  • 190
0

You can also use Aggregate extension method:

var result = people.Aggregate((p1, p2) => p1.Person.FullName+ ", " + p2.Person.FullName);
Pavle Gartner
  • 659
  • 1
  • 7
  • 21