How to combine an array into a semicolon string for 3 elements in C #

Say I have an array.

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

I want to join them with a 3-element comma, as shown below.

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

I know I can use

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

But it gives me a result like

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

Does anyone have any ideas?

+6
source share
4 answers

One quick and easy way to group your items in pieces 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 .GroupBy overload, which allows you to specify an element selector, as I think this is a cleaner way to do this. Included from @Jamiec answer.

What's going on here:

  • We project each temp element into a new element - an anonymous object with the Char and Index properties.
  • Then we group the resulting Enumerable by the result of integer division between the index of the element and 3. With the second parameter .GroupBy we indicate that we want each element in the group to have the Char property of an anonymous object.
  • Then we call .Select to re-design the grouped elements. This time, our projection function needs to call string.Join , passing each group of strings to this method.
  • At this point, we have an IEnumerable<string> that looks the way we want it, so we just need to call ToArray to create an array from our Enumerable.
+11
source

You can combine the Chunk method ( credit for 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); } } 
+5
source

This can be done by linking the Linq operators 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) ); 

Real-time example: http://rextester.com/AHZM76517

+4
source

You can use MoreLINQ Package:

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

Source: https://habr.com/ru/post/951805/


All Articles