There is a list

var lst = new List<double>(); lst.Add(123); lst.Add(123); lst.Add(2); 

I'm trying to get the index of the maximum element, but I can not figure out how to return the last maximum element. At the moment, he says that the maximum element is 0, which is true in principle, but I need the maximum last index.

 public int MaxIndex<T>(IEnumerable<T> source) { IComparer<T> comparer = Comparer<T>.Default; using (var iterator = source.GetEnumerator()) { if (!iterator.MoveNext()) { throw new InvalidOperationException("Empty sequence"); } int maxIndex = 0; T maxElement = iterator.Current; int index = 0; while (iterator.MoveNext()) { index++; T element = iterator.Current; if (comparer.Compare(element, maxElement) > 0) { maxElement = element; maxIndex = index; } } return maxIndex; } } 
  • one
    comparer.Compare(element, maxElement) > 0 - replace> with> =, then the index will point to the last maximum element encountered. - kmv

1 answer 1

 using System.Linq; ... lst.LastIndexOf(lst.Max());