Obtain the index of the maximum element

前端 未结 9 1588
梦谈多话
梦谈多话 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:46

    Here's the non-linq method if you like:

    private int ReturnMaxIdx(List intList)
            {
                int MaxIDX = -1;
                int Max = -1;
    
                for (int i = 0; i < intList.Count; i++)
                {
                    if (i == 0)
                    {
                        Max = intList[0];
                        MaxIDX = 0;
                    }
                    else
                    {
                        if (intList[i] > Max)
                        {
                            Max = intList[i];
                            MaxIDX = i;
                        }
                    }
                }
    
                return MaxIDX;
            }
    

    This is a single pass through the list at least.

    Hope this helps,

    Kyle

提交回复
热议问题