Given such a list:
List intList = new List();
intList.Add(5);
intList.Add(10);
intList.Add(15);
Here's a custom LINQ method which I believe does what you want. (I previously had another which does a projection, but you can just call Select to do that, as you only need the index.)
public static int MaxIndex<T>(this 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;
}
}
Use a custom function, using Max() and IndexOf() cost more.
public static class Extensions
{
public static int MaxIndex<T>(this IEnumerable<T> TSource)
{
int i = -1;
using (var iterator = TSource.GetEnumerator())
while (iterator.MoveNext())
i++;
return i;
}
}
Here is my crack at this problem. I returned -1 instead of throwing an exception because this is what the FindIndex function does and I find it very convenient.