如何连接字符串在C#中

问题描述:

我有一个字符串被称为人的名单。我想结合这些并用逗号分隔它们并将它们存储在一个名为totalPeopleNames的变量中。这是我有什么,但它不工作:如何连接字符串在C#中

string totalPeopleNames = null; 

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

可能重复?](http://*.com/questions/4884050/create-comma-separated-strings-c)或http://*.co m/questions/330493/join-collection-of-objects-into-comma-separated-string或http://*.com/questions/2917571/linq-how-do-i-concatenate-a-list-of-整数 - 到 - 逗号分隔字符串 –

var totalPeopleNames = String.Join(", ",people.Select(p=>p.Person.FullName)) 

一个可能的解决方案:

string totalPeopleNames = ""; 

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

更好:

看C# “Text.StringBuilder”:

您也可以使用聚合扩展方法:

var result = people.Aggregate((p1, p2) => p1.Person.FullName+ ", " + p2.Person.FullName); 

最简单的方法是使用[创建逗号分隔字符串C#的String.Join

var names = String.Join(", ", people.Select(p => p.Person.FullName));