C# find highest array value and index C# find highest array value and index arrays arrays

C# find highest array value and index


This is not the most glamorous way but works.

(must have using System.Linq;)

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


int[] anArray = { 1, 5, 2, 7 };// Finding maxint m = anArray.Max();// Positioning maxint p = Array.IndexOf(anArray, m);


If the index is not sorted, you have to iterate through the array at least once to find the highest value. I'd use a simple for loop:

int? maxVal = null; //nullable so this works even if you have all super-low negativesint index = -1;for (int i = 0; i < anArray.Length; i++){  int thisNum = anArray[i];  if (!maxVal.HasValue || thisNum > maxVal.Value)  {    maxVal = thisNum;    index = i;  }}

This is more verbose than something using LINQ or other one-line solutions, but it's probably a little faster. There's really no way to make this faster than O(N).