找到C#中int数组的最小值 [英] find the min value in int array with C#
本文介绍了找到C#中int数组的最小值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我怎么能找到用C#
推荐答案
使用LINQ在INT ARRY min值:
With LINQ:
int min = theArray.Min();
注意,如果没有这将错误的任何的元素;检查。长度
第一(或者,项目 INT?
,但会增加开销)。
note that this will error if there aren't any elements; check the .Length
first (or alternatively, project to int?
, but that adds overhead).
如果你没有可用的LINQ,那么也许:
If you don't have LINQ available, then perhaps:
public static int Min(int[] arr) {
switch (arr.Length) {
case 0: throw new InvalidOperationException();
case 1: return arr[0];
case 2: return Math.Min(arr[0], arr[1]);
default:
int min = arr[0];
for (int i = 1; i < arr.Length; i++) {
if (arr[i] < min) min = arr[i];
}
return min;
}
}
这篇关于找到C#中int数组的最小值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文