【问题标题】:How to convert IEnumerable<string> to one comma separated string?如何将 IEnumerable<string> 转换为一个逗号分隔的字符串?
【发布时间】:2011-11-20 20:53:44
【问题描述】:

假设出于调试目的,我想快速将 IEnumerable 的内容转换为单行字符串,其中每个字符串项以逗号分隔。我可以在一个带有 foreach 循环的辅助方法中做到这一点,但这既不有趣也不简短。可以使用linq吗?其他一些简短的方式?

【问题讨论】:

标签: c# string linq collections ienumerable


【解决方案1】:
using System;
using System.Collections.Generic;
using System.Linq;

class C
{
    public static void Main()
    {
        var a = new []{
            "First", "Second", "Third"
        };

        System.Console.Write(string.Join(",", a));

    }
}

【讨论】:

    【解决方案2】:
    string output = String.Join(",", yourEnumerable);
    

    String.Join Method (String, IEnumerable

    连接构造的 IEnumerable 集合的成员 输入字符串,在每个成员之间使用指定的分隔符。

    【讨论】:

      【解决方案3】:
      collection.Aggregate("", (str, obj) => str + obj.ToString() + ",");
      

      【讨论】:

      • 这会在末尾添加一个多余的逗号,但您可以添加.TrimEnd(',') 来去掉它。
      • 这样做你就不需要在最后修剪了collection.Aggregate((str, obj) =&gt; str + "," + obj.ToString());
      • 请注意,这是一个潜在的性能问题。 Enumerable.Aggregate 方法使用加号来连接字符串。它比 String.Join 方法慢得多。
      【解决方案4】:
      IEnumerable<string> foo = 
      var result = string.Join( ",", foo );
      

      【讨论】:

      • .NET 需要 String.Join 末尾的 .ToArray()
      【解决方案5】:

      (a) 设置 IEnumerable:

              // In this case we are using a list. You can also use an array etc..
              List<string> items = new List<string>() { "WA01", "WA02", "WA03", "WA04", "WA01" };
      

      (b) 将 IEnumerable Together 连接成一个字符串:

              // Now let us join them all together:
              string commaSeparatedString = String.Join(", ", items);
      
              // This is the expected result: "WA01, WA02, WA03, WA04, WA01"
      

      (c) 出于调试目的:

              Console.WriteLine(commaSeparatedString);
              Console.ReadLine();
      

      【讨论】:

        【解决方案6】:

        将大数组的字符串连接成一个字符串,不要直接使用+,使用StringBuilder一一迭代,或者String.Join一键搞定。

        【讨论】:

        • OT:对于 3 个操作数的串联,编译器会将这些操作转换为对 string.Append 方法的一次调用,该方法采用 3 个参数。所以超过 3 个操作数,StringBuilder 就派上用场了。
        猜你喜欢
        • 1970-01-01
        • 2011-10-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-18
        相关资源
        最近更新 更多