连接列表项属性

3

我希望找到一种优雅的方式来创建一个可读的表单,以显示 Generic.List 中所有条目的某些属性。

让我举个例子来说明。我有一个这样的数据结构:

public class InfoItem {
    public string Name { get; set; }
    public string Description { get; set; }
}

以下是我在代码中如何使用它:

List<InfoItem> data = new List<InfoItem>();
data.Add(new InfoItem() { Name = "Germany", Description = "Describes something" });
data.Add(new InfoItem() { Name = "Japan", Description = "Describes something else" });
data.Add(new InfoItem() { Name = "Austria", Description = "And yet something else" });

现在,我想得到的是一个字符串,如“德国,日本,奥地利”。是否有一些LINQ或泛型魔法可以比这个原始循环更好地完成它?

string readableNames = "";
foreach (var item in data) {
    readableNames += item.Name + ", ";
}
readableNames = readableNames.TrimEnd(new char[] { ',', ' ' });
2个回答

4

假设使用v4+(我认为这是一个很好的假设),否则你将不得不将其转换为string[]而不是IEnumerable<string> - Rune FS
谢谢,它几乎完美地工作了!由于它是 .Net 3.5,我仍然需要在 .Select 后添加 .ToArray() - naivists
没问题。毕竟我的假设是错误的 :), 但我看到你已经处理好了。 - Zbigniew

2

简单易学

var str = String.Join(", ", data.Select(x => x.Name));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接