Obtain the index of the maximum element
this way :
var maxIndex = foo.IndexOf(foo.Max());
Here is a simple* and relatively 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.
* Simplicity is relative. The aim here was to reach a balance of readability and still only scan the list once.
** The allocation of lots of new objects during the Select
is probably wasteful. As some people tested, it doesn't perform well for large lists.
EDIT 1: empty list check added.
EDIT 2: added caveats about performance.