Alex Rivera | Logout

Obtain the index of the maximum element

Asked 2009-07-16T08:26:43.683
28

Given such a list:

        List<int> intList = new List<int>();
        intList.Add(5);
        intList.Add(10);
        intList.Add(15);
        intList.Add(46);

how do you obtain the index of the maximum element in the list? In this case, it's at index 3.

Edit: It's a shame that standard LINQ doesn't ship this functionalities.

Edit
Report

1 Answer

3

I can't improve on Jon Skeet's answer for the general case, so I am going for the 'high performance' prize in the specific case of a list of ints.

public static class Extensions
{
    public static int IndexOfMaximumElement(this IList<int> list)
    {
        int size = list.Count;

        if (size < 2)
            return size - 1;

        int maxValue = list[0];
        int maxIndex = 0;

        for (int i = 1; i < size; ++i)
        {
            int thisValue = list[i];
            if (thisValue > maxValue)
            {
                maxValue = thisValue;
                maxIndex = i;
            }
        }

        return maxIndex;
    }
answered 2009-07-16T09:07:35.830

Your Answer