从数组中获取值并添加到一个字符串中
本文关键字:一个 字符串 添加 获取 数组 | 更新日期: 2023-09-27 18:35:52
对象Book
具有Author
,其属性Name
类型为string
。
我想遍历所有作者并将其名称字符串添加到用逗号分隔的一个字符串(不是数组)中,因此此字符串应位于 as
string authorNames = "Author One, Author two, Author three";
string authorNames = string.Empty;
foreach(string item in book.Authors)
{
string fetch = item.Name;
??
}
可以将 string.Join
函数与 LINQ 一起使用
string authorNames = string.Join(", ", book.Authors.Select(a => a.Name));
您可以使用
string authors = String.Join(", ", book.Authors.Select(a => a.Name));
LINQ 是 C# 中要走的路,但为了解释起见,这里是如何显式编码:
string authorNames = string.Empty;
for(int i = 0; i < book.Authors.Count(); i++)
{
if(i > 0)
authorNames += ", ";
authorNames += book.Authors[i].Name;
}
你也可以遍历它们,并将它们附加到authorNames中,并在最后添加一个逗号,完成后只需修剪最后一个逗号。
string authorNames = string.Empty;
foreach(string author in book.Authors)
{
string authorNames += author.Name + ", ";
}
authorNames.TrimEnd(',');
使用 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);
}