【问题标题】:How to join array to string with comma per 3 items in c#如何在c#中每3个项目用逗号将数组连接到字符串
【发布时间】:2013-08-17 16:08:53
【问题描述】:

假设我有一个数组。

string[] temp = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" };

我想用逗号加入他们,每 3 项如下所示。

string[] temp2 = { "a,b,c", "d,e,f", "g,h,i", "j" };

我知道我可以使用

string temp3 = string.Join(",", temp);

但这给了我结果

"a,b,c,d,e,f,g,h,i,j"

有人有想法吗?

【问题讨论】:

    标签: c# arrays string


    【解决方案1】:

    一种快速简单的方法,将您的项目分成三个部分:

    string[] temp = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" };
    
    string[] temp2 = temp.Select((item, index) => new 
    {
        Char = item,
        Index = index
    })
    .GroupBy(i => i.Index / 3, i => i.Char)
    .Select(grp => string.Join(",", grp))
    .ToArray();
    

    更新为使用 .GroupBy 的重载,允许您指定元素选择器,因为我认为这是一种更简洁的方法。注册自@Jamiec's answer.

    这里发生了什么:

    1. 我们将temp 的每个元素投影到一个新元素中——一个具有CharIndex 属性的匿名对象。
    2. 然后,我们通过项目索引和 3 之间的整数除法结果对生成的 Enumerable 进行分组。使用 .GroupBy 的第二个参数,我们指定我们希望组中的每个项目都是Char 匿名对象的属性。
    3. 然后,我们调用.Select 再次投影分组的元素。这次我们的投影函数需要调用string.Join,将每组字符串传递给该方法。
    4. 此时,我们有一个 IEnumerable<string>,它看起来像我们想要的那样,所以只需调用 ToArray 从我们的 Enumerable 创建一个数组。

    【讨论】:

    • 爱它。干净、简单且易于推断代码试图实现的目标。
    • @Andrew Whitaker 非常感谢。
    • @JoshuaSon:没问题!很高兴能提供帮助。
    【解决方案2】:

    您可以将 Chunk 方法 (credit to CaseyB) 与 string.Join 结合使用:

    string[] temp2 = temp.Chunk(3).Select(x => string.Join(",", x)).ToArray();
    
    /// <summary>
    /// Break a list of items into chunks of a specific size
    /// </summary>
    public static IEnumerable<IEnumerable<T>> Chunk<T>(this IEnumerable<T> source, int chunksize)
    {
        while (source.Any())
        {
            yield return source.Take(chunksize);
            source = source.Skip(chunksize);
        }
    }
    

    【讨论】:

    • 不错的分块实现!
    【解决方案3】:

    可以通过将 Linq 语句链接在一起来完成:

    var grouped = temp.Select( (e,i) => new{ Index=i/3, Item=e})
                  .GroupBy(x => x.Index, x=> x.Item)
                  .Select( x => String.Join(",",x) );
    

    现场示例:http://rextester.com/AHZM76517

    【讨论】:

      【解决方案4】:

      你可以使用MoreLINQ批量:

      var temp3 = temp.Batch(3).Select(b => String.Join(",", b));
      

      【讨论】:

      • 批次来自哪里?
      • @JoshuaSon 有一个链接。您可以从 NuGet 获得 MoreLINQ
      • 哦,我明白了。非常感谢您的快速回答。但我宁愿使用裸 C#。无论如何,再次非常感谢。
      猜你喜欢
      • 2017-09-28
      • 2021-02-05
      • 2014-05-27
      • 2019-02-23
      • 1970-01-01
      • 1970-01-01
      • 2012-08-28
      • 1970-01-01
      • 2019-05-10
      相关资源
      最近更新 更多