-1

对象Book具有类型的Author属性。Namestring

我想遍历所有作者并将其名称字符串添加到以逗号分隔的一个字符串(不是数组)中,因此该字符串应位于 as

string authorNames = "Author One, Author two, Author three";

string authorNames = string.Empty;
foreach(string item in book.Authors)
{
    string fetch = item.Name;
    ??
}
4

5 回答 5

6

您可以将该string.Join函数与 LINQ 一起使用

string authorNames = string.Join(", ", book.Authors.Select(a => a.Name));
于 2013-10-18T11:53:52.000 回答
0

使用 LinQ,有很多方法可以将多个字符串合并为一个字符串。

book.Authors.Select(x => x.Name).Aggregate((x, y) => x + ", " + y);

回答詹姆斯的评论

[TestMethod]
public void JoinStringsViaAggregate()
{
    var mystrings = new[] {"Alpha", "Beta", "Gamma"};
    var result = mystrings.Aggregate((x, y) => x + ", " + y);

    Assert.AreEqual("Alpha, Beta, Gamma", result);
}
于 2013-10-18T11:53:27.990 回答
0

您可以使用

string authors = String.Join(", ", book.Authors.Select(a => a.Name));
于 2013-10-18T11:54:24.117 回答
0

LINQ 是使用 C# 的方式,但出于解释目的,这里是您如何显式编码它的方法:

string authorNames = string.Empty;
for(int i = 0; i < book.Authors.Count(); i++)
{
    if(i > 0)
        authorNames += ", ";
    authorNames += book.Authors[i].Name;
}
于 2013-10-18T11:56:46.230 回答
0

您也可以遍历它们,并将它们附加到 authorNames 并在最后添加一个逗号,完成后只需修剪最后一个逗号。

string authorNames = string.Empty;
foreach(string author in book.Authors)
{
    string authorNames += author.Name + ", ";
}
authorNames.TrimEnd(',');
于 2013-10-18T12:02:03.227 回答