Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to take nth item in array to zth item in array?

Tags:

arrays

c#

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?

like image 522
User2012384 Avatar asked May 07 '15 02:05

User2012384


People also ask

How to get every Nth Element from an array?

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.

What is the index value of nth element of an 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 .


2 Answers

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).

like image 103
Blorgbeard Avatar answered Oct 25 '22 23:10

Blorgbeard


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

var result = String.Join(" ", test.ToList().GetRange(1, 3));
like image 27
DWright Avatar answered Oct 25 '22 22:10

DWright