【问题标题】:c # write one line of code from list to arrayc#将一行代码从列表写入数组
【发布时间】:2021-04-04 05:04:48
【问题描述】:

是否可以在 C# 中将 List<Tag> 对象的 Name 属性与逗号 "," 与行命令结合起来? "World,Tech,Science,Arts"

public class Tag
{
   public int Id { get; set; }
   public string Name { get; set; }
}
List<string> tagNames;
foreach (var tag in tags)
{
   tagNames.add(tag.Name);
}
string result = String.Join(",", tagNames);

我试过了,但是不行

string result = String.Join(",", tags.ForEach(t => t.Name));

【问题讨论】:

  • 你应该使用Select,而不是ForEach,并确保你有using System.Linq;
  • List 的ForEach 对人们对 LINQ 的理解造成的损害比对整个 C# 的好处要大

标签: c# string arraylist


【解决方案1】:

ForEach 运行一段代码。您正在寻找 Select 以不同的形式投射每个元素:

string result = String.Join(",", tags.Select(t => t.Name));

【讨论】:

    【解决方案2】:

    在 C# 中是否可以组合 List 的 Name 属性 带有逗号“,”的对象和行命令?

    另一个使用Aggregate而不是String.Join()的单行:

    string result = tags.Select(t => t.Name).Aggregate((a, b) => (a + "," + b));
    

    【讨论】:

      猜你喜欢
      • 2018-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-03
      • 2012-12-17
      • 2019-04-09
      相关资源
      最近更新 更多