Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy subarray based on index array

Tags:

c#

There are a bunch of answers on how to get a subarray with start and end index or start index and length. But I m looking for a way to get an subarray based on index array. Here is what I have (which works fine but seems clunky).

//sample arrays (could be unordered)
double[] expiry= { 0.99, 0.9, 0.75, 0.60, 0.5, 0.4, ...};
double[] values = { 0.245, 0.24, 0.235, 0.22, 0.21, 0.20, ... };


//find index of all elements meeting criteria in array expiry
int[] expind = expiry
  .Select((b, i) => b == 0.75? i : -1)
  .Where(i => i != -1).ToArray();

//create new arrays of appropriate size
double[] newvalues = new double[expind.Length];

//populate new arrays based on index
for (int i = 0; i < expind.Length; i++)
  newvalues[i] = values[expind[i]];

//check values
foreach (var item in newvalues)
   Console.WriteLine(item);

Is there a more efficient and general way of doing this please?

UPDATE

next attempt (Still not super efficient, but at least loopless):

Array.Sort(expiry, values);     
double criteria = 0.75;
int start = Array.IndexOf(expiry, criteria);
int last = Array.LastIndexOf(expiry, criteria);
int length = last - start + 1;
double[] newvalues2 = new double[length];
Array.Copy(values, start, newvalues2, 0, length);
like image 469
nik Avatar asked Sep 02 '26 09:09

nik


1 Answers

Hi you can find the values in this way using lambda expression:

double[] newVals = values.Where((t, i) => expiry[i] == 0.75).ToArray();
like image 66
aminexplo Avatar answered Sep 05 '26 00:09

aminexplo