考虑到这是一项非常基本的任务,我想不出一个适当的简单方法.你如何获得int数组中最低值的索引?使用Linq/MoreLinq是可能的.到目前为止,我找不到合理的单线.
Ani*_*Ani 22
既然你提到了MoreLinq,那怎么样:
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;
Run Code Online (Sandbox Code Playgroud)
另一种选择:
// Will throw if the array is empty.
// Requires two passes over the array.
int minIndex = Array.IndexOf(array, array.Min());
Run Code Online (Sandbox Code Playgroud)
您当然可以编写自己的扩展方法:
// 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;
}
Run Code Online (Sandbox Code Playgroud)
通过一些努力,您可以通过接受一个IComparer<T>默认值来将其概括为任何类型Comparer<T>.Default.
sho*_*zer 11
LINQ可能不是解决此问题的最佳解决方案,但这是另一个变体O(n).它不排序,只遍历数组一次.
var arr = new int[] { 3, 1, 0, 5 };
int pos = Enumerable.Range(0, arr.Length)
.Aggregate((a, b) => (arr[a] < arr[b]) ? a : b); // returns 2
Run Code Online (Sandbox Code Playgroud)
更新:直接回答原始问题,我就是这样做的:
var arr = new int[] { 3, 1, 0, 5 };
int pos = 0;
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] < arr[pos]) { pos = i; }
}
// pos == 2
Run Code Online (Sandbox Code Playgroud)
不,它不使用LINQ.是的,它不止一条线.但它非常简单而且速度非常快.将它变成一个小小的方法,并从一行中的任何地方调用它:pos = FindMinIndex(arr);
不是很友善,但......
array.Select((n, i) => new { index = i, value = n })
.OrderBy(item => item.value)
.First().index
Run Code Online (Sandbox Code Playgroud)