How do you find the maximum element index?
-
Got a list.
var lst = new List<double>(); lst.Add(123); lst.Add(123); lst.Add(2);
I'm trying to get a maximum element index, but I can't figure out how to get the last maximum element back. At the moment, he says that the maximum element 0, which is in principle true, but I need the maximum final 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; } }
-
using System.Linq; ... lst.LastIndexOf(lst.Max());