0

I saw the article : C# find highest array value and index

I have another question is : How to find the other index if there exists duplicate value?

Assume that array is

int[] anArray = { 1, 5, 2, 7 , 7 , 3};

int maxValue = anArray.Max();
int maxIndex = anArray.ToList().IndexOf(maxValue);

How to find the other index if I use the method in this article?

3 Answers 3

4

Your question is "how do I find the other index" but it should be "how do I find all other indexes" because there might be multiple.

int[] anArray = { 1, 5, 2, 7, 7, 3 };

int maxValue = anArray.Max();
int maxIndexes =
 anArray
 .Select((x, i) => new { x, i }) //add indexes to sequence
 .Where(x => x == maxValue) //filter on maxValue
 .Select(x => x.i) //only select index
 .ToList(); //ToList is optional

If you only want the last one, or you are sure that there is at most one such indexes, just end the query with .Last() or similar.

0

This answer your question. Use LastIndexOf() will find the last index of the value you specify ;)

This way you will get the last index and the last index of this value:

int maxValue = anArray.Max()
int index = anArray.ToList().LastIndexOf(maxValue);
0

Refer to accepted answer of Get indexes of all matching values from list using Linq

All of the LINQ methods are carefully designed to only ever iterate the source sequence once (when they are iterated once). Therefore we use Enumerable.Range expressions from LINQ to loop

int[] anArray = { 1, 5, 2, 7 , 7 , 3};
int maxValue = anArray.Max();

var result = Enumerable.Range(0, anArray.Count())
 .Where(i => anArray[i] == maxValue)
 .ToList();

Extra info : Enumerable.Range automatically excludes the highest index, anArray.Count().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.