Obtain the index of the maximum element

前端 未结 9 1528
梦谈多话
梦谈多话 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<T>(this IEnumerable<T> source)
    {
        IComparer<T> comparer = Comparer<T>.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;
        }
    }
    
    0 讨论(0)
  • 2020-12-28 15:49

    Use a custom function, using Max() and IndexOf() cost more.

    0 讨论(0)
  • 2020-12-28 15:50
    public static class Extensions
    {
        public static int MaxIndex<T>(this IEnumerable<T> TSource)
        {
            int i = -1;
            using (var iterator = TSource.GetEnumerator())
                while (iterator.MoveNext())
                    i++;
            return i;
        }
    }
    

    Here is my crack at this problem. I returned -1 instead of throwing an exception because this is what the FindIndex function does and I find it very convenient.

    0 讨论(0)
提交回复
热议问题