Get array index values ​​from the 1000 largest records inside the array using LINQ

I would like to have nice clean LINQ code that can get an array of index values ​​from the 1000 largest values ​​inside the array.

For instance:

int[] IndexArray = ArrayWithValues.Return_Indexes_Of_1000_Biggest_Values

The code is clearly dummy, this is just to illustrate what I need.

UPDATE

I completely forgot to say that I need a second functionality. I have a second array, and I need to get all the values ​​in the second array, which has the same indexes as inside the IndexArray.

I can do this easily with loops and all that, but the code is big and I want to learn to use LINQ more often, but at the moment LINQ is still very foreign to me.

I looked at similar questions asked here, but I was not able to change the code to set my needs, because people usually only need values, not value indices.

Thanks for the help!

+5
source share
1 answer

Something like this should work. It uses overloading Select, which allows you to include a second input, which is the index of the element in the sequence.

var indexArray = sourceArray
                   .Select((value, index) => new { value, index })
                   .OrderByDescending(item => item.value)
                   .Take(1000)
                   .Select(item => item.index)
                   .ToArray();

Just project the value and index into the object, order it by value, take the top 1000 elements, and then just select the indexes before converting to an array.

Testing, taking the top 5 indices from an array { 10, 4, 6, 8, 2, 3, 5, 1, 9, 7 }, gives { 0, 8, 3, 9, 2 }which displays the values { 10, 9, 8, 7, 6 }.


, , , IndexOutOfBoundsException.

.Select(item => otherArray[item.index])
.ToArray();

, , Enumerable.Zip.

+7

All Articles