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 max
int m = anArray.Max();

// Positioning max
int 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 negatives
int 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).


A succinct one-liner:

var (number, index) = anArray.Select((n, i) => (n, i)).Max();

Test case:

var anArray = new int[] { 1, 5, 7, 4, 2 };
var (number, index) = anArray.Select((n, i) => (n, i)).Max();
Console.WriteLine($"Maximum number = {number}, on index {index}.");
// Maximum number = 7, on index 2.

Features:

  • Uses Linq (not as optimized as vanilla, but the trade-off is less code).
  • Does not need to sort.
  • Computational complexity: O(n).
  • Space complexity: O(n).

Remarks:

  • Make sure the number (and not the index) is the first element in the tuple because tuple sorting is done by comparing tuple items from left to right.

The obligatory LINQ one[1]-liner:

var max = anArray.Select((value, index) => new {value, index})
                 .OrderByDescending(vi => vi.value)
                 .First();

(The sorting is probably a performance hit over the other solutions.)

[1]: For given values of "one".