How would you get the index of the lowest value in an int array?

前端 未结 5 1803
旧巷少年郎
旧巷少年郎 2020-12-28 16:45

Considering that this is a very basic task, I could not think of an appropriately easy way to do it. How would you get the index of the lowest value in an int array? Using L

5条回答
  •  Happy的楠姐
    2020-12-28 17:40

    Since you mention MoreLinq, how about:

    int[] array = ..
    
    // Will throw if the array is empty.
    // If there are duplicate minimum values, the one with the smaller
    // index will be chosen.
    int minIndex = array.AsSmartEnumerable()
                        .MinBy(entry => entry.Value)
                        .Index;
    

    Another alternative:

    // Will throw if the array is empty.
    // Requires two passes over the array. 
    int minIndex = Array.IndexOf(array, array.Min());
    

    You could of course write your own extension-method:

    // Returns last index of the value that is the minimum.
    public static int IndexOfMin(this IEnumerable source)
    {
       if(source == null)
         throw new ArgumentNullException("source");
    
       int minValue = int.MaxValue;
       int minIndex = -1;
       int index = -1;
    
       foreach(int num in source)
       {
          index++;
    
          if(num <= minValue)
          {
             minValue = num;
             minIndex = index;
          }
       }
    
       if(index == -1)
         throw new InvalidOperationException("Sequence was empty");
    
       return minIndex;
    }
    

    With some effort, you can generalize this to any type by accepting an IComparer, defaulting to Comparer.Default.

提交回复
热议问题