Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get array items by index

Tags:

arrays

c#

I have two arrays, one with values an one with indices

int[] items = { 1, 2, 3, 7, 8, 9, 13, 16, 19, 23, 25, 26, 29, 31, 35, 36, 39, 45 };
int[] indices = { 1, 3, 5, 6, 7, 9 };

now I want a result array from the items selected by the indices of indices array

// 2, 7, 9, 13, 19
int[] result = new []{ items[1], items[3], items[5], items[6], items[7], items[9] }; 

Question: Is there a more generic approach for this?

like image 690
Impostor Avatar asked May 04 '18 13:05

Impostor


People also ask

How do you use indexOf for array of objects?

To find the index of an object in an array, by a specific property: Use the map() method to iterate over the array, returning only the value of the relevant property. Call the indexOf() method on the returned from map array. The indexOf method returns the index of the first occurrence of a value in an array.

How do you select an index of an array?

To specify the indexes, enter a value in the Input array indexes field of the Cardinality properties page for the transform. The indexes are 1-based, which means that the first element of the array is referenced as 1, the second element as 2, and so on.

How do you get the index of an element in a list in JS?

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.


1 Answers

var results = Array.ConvertAll(indices, i => items[i]);
like image 79
Marc Gravell Avatar answered Oct 05 '22 21:10

Marc Gravell