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;
  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.

* 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.

Tags:

C#

Linq