Obtain the index of the maximum element

前端 未结 9 1570
梦谈多话
梦谈多话 2020-12-28 15:03

Given such a list:

        List intList = new List();
        intList.Add(5);
        intList.Add(10);
        intList.Add(15);
                


        
9条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-28 15:40

    Here is my solution:

    public static int IndexOfMax(this IList source)
    {
        if (source == null)
            throw new ArgumentNullException("source");
        if (source.Count == 0)
            throw new InvalidOperationException("List contains no elements");
    
        int maxValue = source[0];
        int maxIndex = 0;
        for (int i = 1; i < source.Count; i++)
        {
            int value = source[i];
            if (value > maxValue)
            {
                maxValue = value;
                maxIndex = i;
            }
        }
        return maxIndex;
    }
    

提交回复
热议问题