How to join array to string with comma per 3 items in c#
arrays, c#, string
Solution
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:
- We're projecting each element of `temp` into a new element--an anonymous object with `Char` and `Index` properties.
- 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.
- 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.
- 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.
Problem
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?