C# find highest array value and index

Edmund Rojas picture Edmund Rojas · Dec 7, 2012 · Viewed 346.6k times · Source

So I have an unsorted numeric array int[] anArray = { 1, 5, 2, 7 }; and I need to get both the value and the index of the largest value in the array which would be 7 and 3, how would I do this?

Answer

sa_ddam213 picture sa_ddam213 · Dec 7, 2012

This is not the most glamorous way but works.

(must have using System.Linq;)

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