Obtain the index of the maximum element

前端 未结 9 1576
梦谈多话
梦谈多话 2020-12-28 15:03

Given such a list:

        List intList = new List();
        intList.Add(5);
        intList.Add(10);
        intList.Add(15);
                


        
9条回答
  •  再見小時候
    2020-12-28 15:36

    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, 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 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 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;
        }
    }
    

提交回复
热议问题