如何使用 LINQ 获取数组中最大值的索引? [英] How do I get the index of the highest value in an array using LINQ?

查看:43
本文介绍了如何使用 LINQ 获取数组中最大值的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个双精度数组,我想要最高值的索引.这些是我迄今为止提出的解决方案,但我认为必须有一个更优雅的解决方案.想法?

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 solution. Ideas?

double[] score = new double[] { 12.2, 13.3, 5, 17.2, 2.2, 4.5 };
int topScoreIndex = score.Select((item, indx) => new {Item = item, Index = indx}).OrderByDescending(x => x.Item).Select(x => x.Index).First();

topScoreIndex = score.Select((item, indx) => new {Item = item, Index = indx}).OrderBy(x => x.Item).Select(x => x.Index).Last();

double maxVal = score.Max();
topScoreIndex = score.Select((item, indx) => new {Item = item, Index = indx}).Where(x => x.Item == maxVal).Select(x => x.Index).Single();

推荐答案

我建议编写您自己的扩展方法(编辑为具有 IComparable 约束的通用方法.)

I suggest writing your own extension method (edited to be generic with an IComparable<T> constraint.)

public static int MaxIndex<T>(this IEnumerable<T> sequence)
    where T : IComparable<T>
{
    int maxIndex = -1;
    T maxValue = default(T); // Immediately overwritten anyway

    int index = 0;
    foreach (T value in sequence)
    {
        if (value.CompareTo(maxValue) > 0 || maxIndex == -1)
        {
             maxIndex = index;
             maxValue = value;
        }
        index++;
    }
    return maxIndex;
}

请注意,如果序列为空,则返回 -1.

Note that this returns -1 if the sequence is empty.

关于特点的一句话:

  • 这适用于只能枚举一次的序列 - 这有时非常重要,并且通常是 IMO 理想的功能.
  • 内存复杂度为 O(1)(相对于排序的 O(n))
  • 运行时复杂度为 O(n)(相对于排序的 O(n log n))

至于这是否是LINQ":如果它被列为标准的LINQ查询运算符之一,你会认为它是LINQ吗?它是否感觉特别陌生或与其他 LINQ 运算符不同?如果 MS 将其作为新运算符包含在 .NET 4.0 中,它会是 LINQ 吗?

As for whether this "is LINQ" or not: if it had been included as one of the standard LINQ query operators, would you count it as LINQ? Does it feel particularly alien or unlike other LINQ operators? If MS were to include it in .NET 4.0 as a new operator, would it be LINQ?

如果您真的非常非常喜欢使用 LINQ(而不仅仅是获得一个优雅的解决方案),那么这里仍然是 O(n) 并且只计算一次序列:

If you're really, really hell-bent on using LINQ (rather than just getting an elegant solution) then here's one which is still O(n) and only evaluates the sequence once:

int maxIndex = -1;
int index=0;
double maxValue = 0;

int urgh = sequence.Select(value => {
    if (maxIndex == -1 || value > maxValue)
    {
        maxIndex = index;
        maxValue = value;
    }
    index++;
    return maxIndex;
 }).Last();

这太可怕了,我完全不建议您使用它 - 但它会起作用.

It's hideous, and I don't suggest you use it at all - but it will work.

这篇关于如何使用 LINQ 获取数组中最大值的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆