How to transfer the nth element in an array to the zth element in an array?

I created an array like this:

string[] test = new string[]{"apple", "banana", "tomato", "pineapple", "grapes"}; 

And now I would like to take the 2nd, 3rd and 4th positions in the array and merge, I am currently using this code:

 string result = ""; for(int i = 1; i < 4; i++) { result += test[i] + " "; } 

So the result would be banana tomato pineapple , and this works great.

And I would like to ask if there is a standard or better way to achieve this?

+7
arrays c #
source share
3 answers

You can write this more briefly:

 string result = string.Join(" ", test.Skip(1).Take(3)); 

In addition, this has the bonus of not adding end space (which your code does).

+14
source share

Another option that uses GetRange , which is very natural for this:

 var result = String.Join(" ", test.ToList().GetRange(1, 3)); 
+5
source share

I have a simple solution.

 string result = ""; for(int i = 0; i <= [upper bound] ; i++) { if i >= [n] and i <= [z] then { result += test[i] + " "; } } 

You can set n and z as the range you want.

-one
source share

All Articles