6

Let's say that I have an array.

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

I want to join them with comma per 3 items like below.

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

I know I can use

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

But this gives me the result as

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

Does anyone have an idea?

Joshua Son
  • 1,839
  • 6
  • 31
  • 51

4 Answers4

13

One quick and easy way, grouping your items in chunks of three:

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();

Updated to use the overload of .GroupBy that allows you to specify an element selector since I think this is a cleaner way to do it. Incorporated from @Jamiec's answer.

What's going on here:

  1. We're projecting each element of temp into a new element--an anonymous object with Char and Index properties.
  2. We're then grouping the resulting Enumerable by the result of integer division between the index of the item and 3. With the second parameter to .GroupBy, we're specifying that we want each item in the group to be the Char property of the anonymous object.
  3. Then, we're calling .Select to project the grouped elements again. This time our projection function needs to call string.Join, passing each group of strings to that method.
  4. At this point we have an IEnumerable<string> that looks the way we want it to, so it's just a matter of calling ToArray to create an array from our Enumerable.
Community
  • 1
  • 1
Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
5

You can combine a Chunk method (credit to CaseyB) with 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);
    }
}
Community
  • 1
  • 1
Tim S.
  • 55,448
  • 7
  • 96
  • 122
4

It can be done by chaining Linq statements together:

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

Live example: http://rextester.com/AHZM76517

Jamiec
  • 133,658
  • 13
  • 134
  • 193
3

You can use MoreLINQ Batch:

var temp3 = temp.Batch(3).Select(b => String.Join(",", b));
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459