获得最大的元素的索引 [英] Obtain the Index of the Maximum Element

查看:94
本文介绍了获得最大的元素的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定这样一个列表:

 列表< INT> intList中=新名单< INT>(); 
intList.Add(5);
intList.Add(10);
intList.Add(15);
intList.Add(46);



你如何获得在列表中的最大元素的索引?在这种情况下,它在指数3



编辑:这是一个耻辱,标准的LINQ不发货此功能


解决方案

下面是一个简单而有效的解决方案:

  INT indexMax 
=!intList.Any()? -1:
intList中
。选择((价值指数)=>新建{值=值,指数=指数})
.Aggregate((A,B)=>( a.value中> b.Value)A:b)
的.index;




  1. !intList.Any ()? -1:将强制 1 如果列表是空的;


  2. 选择将项目中的每个 INT 元素放入一个匿名类型具有两个属性:首页;


  3. 汇总将得到最高的元素;


  4. 最后,我们得到所选元素的首页




编辑1:空单增加检查


Given such a list:

        List<int> intList = new List<int>();
        intList.Add(5);
        intList.Add(10);
        intList.Add(15);
        intList.Add(46);

how do you obtain the index of the maximum element in the list? In this case, it's at index 3.

Edit: It's a shame that standard LINQ doesn't ship this functionalities.

解决方案

Here is a simple and efficient solution:

int indexMax
    = !intList.Any() ? -1 :
    intList
    .Select( (value, index) => new { Value = value, Index = index } )
    .Aggregate( (a, b) => (a.Value > b.Value) ? a : b )
    .Index;

  1. The !intList.Any() ? -1 : will force a -1 if the list is empty;

  2. The Select will project each int element into an anonymous type with two properties: Value and Index;

  3. The Aggregate will get the element with the highest Value;

  4. Finally, we get the Index of the chosen element.

EDIT 1: empty list check added.

这篇关于获得最大的元素的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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