Here's how to do it in one (long) line using LINQ, with just a single pass through the collection. It should work for any IEnumerable<int>
, not just lists.
int maxIndex = intList
.Select((x, i) => new { Value = x, Index = i })
.Aggregate
(
new { Value = int.MinValue, Index = -1 },
(a, x) => (a.Index < 0) || (x.Value > a.Value) ? x : a,
a => a.Index
);
Here's the non-LINQ equivalent of the above, using a foreach
loop. (Again, just a single pass through the collection, and should work for any IEnumerable<int>
.)
int maxIndex = -1, maxValue = int.MinValue, i = 0;
foreach (int v in intList)
{
if ((maxIndex < 0) || (v > maxValue))
{
maxValue = v;
maxIndex = i;
}
i++;
}
If you know that the collection is an IList<int>
then a plain for
loop is probably the easiest solution:
int maxIndex = -1, maxValue = int.MinValue;
for (int i = 0; i < intList.Count; i++)
{
if ((maxIndex < 0) || (intList[i] > maxValue))
{
maxValue = intList[i];
maxIndex = i;
}
}