您将如何获取int数组中最小值的索引? [英] How would you get the index of the lowest value in an int array?

查看:311
本文介绍了您将如何获取int数组中最小值的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑到这是一项非常基本的任务,我想不出一种合适的简便方法。您将如何获取int数组中最小值的索引?可以使用Linq / MoreLinq。到目前为止,我还找不到一个合理的单行代码。

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.

推荐答案

既然您提到MoreLinq,怎么办:

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;

另一种选择:

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

通过一些努力,您可以通过接受 IComparer< T> ,默认值为 Comparer< T>。默认

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

这篇关于您将如何获取int数组中最小值的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆