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

前端 未结 9 2101
死守一世寂寞
死守一世寂寞 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:16

    Meh, why make it overcomplicated? This is the simplest way.

    var indexAtMax = scores.ToList().IndexOf(scores.Max());
    

    Yeah, you could make an extension method to use less memory, but unless you're dealing with huge arrays, you will never notice the difference.

    0 讨论(0)
  • 2020-11-27 19:16

    This isn't the only Aggregate based solution, but this is really just a single line solution.

    double[] score = new double[] { 12.2, 13.3, 5, 17.2, 2.2, 4.5 };
    
    var max = score.Select((val,ix)=>new{val,ix}).Aggregate(new{val=-1.0,ix=-1},(z,last)=>z.val>last.val?z:last);
    
    Console.WriteLine ("maximum value is {0}", max.val );
    Console.WriteLine ("index of maximum value is {0}", max.ix );
    
    0 讨论(0)
  • 2020-11-27 19:18

    Try this one which is completely LINQ and has the best performance:

    var indexAtMax = scores.Select((x, i) => new { x, i })
                .Aggregate((a, a1) => a.x > a1.x ? a : a1).i;
    
    0 讨论(0)
提交回复
热议问题