【问题标题】:Convert an array of objects to string [closed]将对象数组转换为字符串 [关闭]
【发布时间】:2018-11-23 08:35:16
【问题描述】:

我有Person[] people,我怎样才能将此数组转换为包含每个PersonName 的CSV 的字符串?

John, Donald, Jessika, ...

【问题讨论】:

    标签: c# arrays linq .net-4.5


    【解决方案1】:
    string.Join(", ", people.Select(p => p.Name));
    

    【讨论】:

    • 感谢您没有发表评论,只是正确而简短地提出了问题;)
    • @Rawling 有见地,我会记住这一点。谢谢。
    • @Serge 没有问题,一切都很好:)。
    • @Rawling,你经常在人名中看到昏迷吗? )
    【解决方案2】:

    最简单的方法是:

    string.Join(", ", people.Select(p => p.Name));
    

    但如果你不理解上述方法,你可以随时使用循环

    StringBuilder csv = new StringBuilder();
    foreach (String person in people)
    {
         csv.Append(person + ",");
    }
    

    【讨论】:

      【解决方案3】:

      您也可以为此使用 linq:

      people
          .Select(x => x.Name)
          .Cast<string> //if needed
          .Aggregate((current, next) => $"{current}, {next}");
      

      【讨论】:

      • 我不明白为什么需要在字符串中转换名称...有需要吗?
      • @Serge 如果名字已经是一个字符串那么当然不是:)
      • 通常名称是一个字符串;)谢谢
      • 另外,我注意到字符串的“$”特性不适合 .net 4.5 版本;)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-21
      • 2018-05-09
      • 1970-01-01
      • 2021-05-24
      • 1970-01-01
      • 2013-09-17
      相关资源
      最近更新 更多