我有一个对象
public class Title
{
public int Id {get; set; }
public string Title {get; set; }
}
如何在
List<Title>
中加入所有带有“-”的标题?
最佳答案
我认为这应该给你你正在寻找的东西。这将从每个对象中选择 Title 属性到一个字符串数组中,然后将该数组的所有元素连接到一个 '-' 分隔的字符串中。
List<Title> lst = new List<Title>
{
new Title{Id = 1, Title = "title1"},
new Title{Id = 2, Title = "title2"}
}
String.Join("-", lst.Select(x => x.Title).ToArray());
如果您使用 .NET 4.0 或更高版本,现在有一个 overload至
String.Join
这将允许您省略 .ToArray()
:String.Join("-", lst.Select(x => x.Title));
关于c#-4.0 - 通用列表.Join,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4548167/