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?
How to get a comma separated string from an array in C#? We can get a comma-separated string from an array using String. Join() method. In the same way, we can get a comma-separated string from the integer array.
To convert an array to a comma-separated string, call the join() method on the array, passing it a string containing a comma as a parameter. The join method returns a string containing all array elements joined by the provided separator.
Answer: Use the split() Method You can use the JavaScript split() method to split a string using a specific separator such as comma ( , ), space, etc. If separator is an empty string, the string is converted to an array of characters.
Using StringBufferCreate an empty String Buffer object. Traverse through the elements of the String array using loop. In the loop, append each element of the array to the StringBuffer object using the append() method. Finally convert the StringBuffer object to string using the toString() method.
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:
temp
into a new element--an anonymous object with Char
and Index
properties..GroupBy
, we're specifying that we want each item in the group to be the Char
property of the anonymous object..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.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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With