我有一个名为 people 的字符串列表。我想将它们组合起来并用逗号分隔它们并将它们存储在一个名为 totalPeopleNames 的变量中。这就是我所拥有的,但它不起作用:
string totalPeopleNames = null;
foreach(var person in people)
{
Enumerable.Concat(totalPeopleNames, ", " + person.Person.FullName);
}
我有一个名为 people 的字符串列表。我想将它们组合起来并用逗号分隔它们并将它们存储在一个名为 totalPeopleNames 的变量中。这就是我所拥有的,但它不起作用:
string totalPeopleNames = null;
foreach(var person in people)
{
Enumerable.Concat(totalPeopleNames, ", " + person.Person.FullName);
}
var totalPeopleNames = String.Join(", ",people.Select(p=>p.Person.FullName))
最简单的方法是使用String.Join
var names = 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);