获得最大的元素的索引 [英] Obtain the Index of the Maximum Element
问题描述
给定这样一个列表:
列表< 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;
-
的
!intList.Any ()? -1:
将强制1
如果列表是空的; -
在
选择
将项目中的每个INT
元素放入一个匿名类型具有两个属性:值
和首页
; -
的
汇总
将得到最高的值
元素; -
最后,我们得到所选元素的
首页
。
编辑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;
The
!intList.Any() ? -1 :
will force a-1
if the list is empty;The
Select
will project eachint
element into an anonymous type with two properties:Value
andIndex
;The
Aggregate
will get the element with the highestValue
;Finally, we get the
Index
of the chosen element.
EDIT 1: empty list check added.
这篇关于获得最大的元素的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!