Alex Rivera | Logout

How do I get the index of the highest value in an array using LINQ?

Asked 2009-01-20T19:23:04.560
31

I have an array of doubles and I want the index of the highest value. These are the solutions that I've come up with so far but I think that there must be a more elegant solution. Ideas?

double[] score = new double[] { 12.2, 13.3, 5, 17.2, 2.2, 4.5 };
int topScoreIndex = score.Select((item, indx) => new {Item = item, Index = indx}).OrderByDescending(x => x.Item).Select(x => x.Index).First();

topScoreIndex = score.Select((item, indx) => new {Item = item, Index = indx}).OrderBy(x => x.Item).Select(x => x.Index).Last();

double maxVal = score.Max();
topScoreIndex = score.Select((item, indx) => new {Item = item, Index = indx}).Where(x => x.Item == maxVal).Select(x => x.Index).Single();
Edit
Report

1 Answer

0

The worst possible complexity of this is O(2N) ~= O(N), but it needs to enumerate the collection two times.

 void Main()
{
    IEnumerable<int> numbers = new int[] { 1, 2, 3, 4, 5 };

    int max = numbers.Max ();
    int index = -1;
    numbers.Any (number => { index++; return number == max;  });

    if(index != 4) {
        throw new Exception("The result should have been 4, but " + index + " was found.");
    }

    "Simple test successful.".Dump();
}
answered 2012-04-10T05:01:56.407

Your Answer