mafu mafu - 3 months ago 14
C# Question

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

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 Linq/MoreLinq is possible. I could not find a reasonable one-liner so far.

Ani Ani
Answer

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<int> 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<T>, defaulting to Comparer<T>.Default.