How do I get the index of the highest value in an array using LINQ?

前端 未结 9 2161
死守一世寂寞
死守一世寂寞 2020-11-27 18:46

I have an array of doubles and I want the index of the highest value. These are the solutions that I\'ve come up with so far but I think that there must be a more elegant so

9条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-27 19:09

    If you want something that looks LINQy, in that it's purely functional, then Jon Skeets' answer above can be recast as:

    public static int MaxIndex(this IEnumerable sequence) where T : IComparable
        {
            return sequence.Aggregate(
                new { maxIndex = -1, maxValue = default(T), thisIndex = 0 },
                ((agg, value) => (value.CompareTo(agg.maxValue) > 0 || agg.maxIndex == -1) ?
                                 new {maxIndex = agg.thisIndex, maxValue = value, thisIndex = agg.thisIndex + 1} :
                                 new {maxIndex = agg.maxIndex, maxValue = agg.maxValue, thisIndex = agg.thisIndex + 1 })).
                maxIndex;
        }
    

    This has the same computational complexity as the other answer, but is more profligate with memory, creating an intermediate answer for each element of the enumerable.

提交回复
热议问题