gpt4 book ai didi

c# - 连接列表项属性

转载 作者:行者123 更新时间:2023-11-30 14:33:15 26 4
gpt4 key购买 nike

我正在寻找一种优雅的方式来创建一个可读的形式,其中包含 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" });

现在,我想要得到的是像“Germany, Japan, Austria”这样的字符串。是否有一些 LINQ 或泛型魔法可以比这个原始循环做得更好?

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

最佳答案

只需使用 string.JoinEnumerable.Select :

string readableNames = string.Join(", ", data.Select(i => i.Name));

关于c# - 连接列表项属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16833793/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com