Obtain the index of the maximum element

c#, linq

Solution

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 each `int` element into an anonymous type with two properties: `Value` and `Index`;

The `Aggregate` will get the element with the highest `Value`;

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.

Problem

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.

Original source