Obtain the index of the maximum element

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

    Here's a custom LINQ method which I believe does what you want. (I previously had another which does a projection, but you can just call Select to do that, as you only need the index.)

    public static int MaxIndex(this IEnumerable source)
    {
        IComparer comparer = Comparer.Default;
        using (var iterator = source.GetEnumerator())
        {
            if (!iterator.MoveNext())
            {
                throw new InvalidOperationException("Empty sequence");
            }
            int maxIndex = 0;
            T maxElement = iterator.Current;
            int index = 0;
            while (iterator.MoveNext())
            {
                index++;
                T element = iterator.Current;
                if (comparer.Compare(element, maxElement) > 0)
                {
                    maxElement = element;
                    maxIndex = index;
                }
            }
            return maxIndex;
        }
    }
    

提交回复
热议问题