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 the 4th item in the array and join together, currently I'm 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 fine.
And I would like to ask if there's a standard or better way to achieve this?
To get every Nth element of an array:Declare an empty array variable. Use a for loop to iterate the array every N elements. On each iteration, push the element to the new array. The final array will contain every Nth element of the original array.
Line 6 : int element = arr[n-1]; And we all know the array is index based that means index always starts with 0. So , the element present in at first position has index value is 0. arr[n-1] : Here inside the square bracket “[]” we give the index value .
You can write it more succinctly like this:
string result = string.Join(" ", test.Skip(1).Take(3));
Also, this has the bonus of not adding a trailing space (which your code does).
Another option, which uses GetRange
, which is very natural for this:
var result = String.Join(" ", test.ToList().GetRange(1, 3));
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