常见求最大值,是数值型数组,这个通常遍历数组方式,或数组排序即可完成。但对于字符串或日期等非数值类型不能处理。下面给出泛型数组的最大值或最大值位置索引的自定义函数。
数组最大值的位置索引
//传入一个数组,求出一个数组的最大值的位置
public static int MaxIndex<T>(T[] arr) where T : IComparable<T>
{
var i_Pos = 0;
var value = arr[0];
for (var i = 1; i < arr.Length; ++i)
{
var _value = arr[i];
if (_value.CompareTo(value) > 0)
{
value = _value;
i_Pos = i;
}
}
return i_Pos;
}
数组最大值
//传入一个数组,求出一个数组的最大值
public static T MaxValue<T>(T[] arr) where T : IComparable<T>
{
var i_Pos = 0;
var value = arr[0];
for (var i = 1; i < arr.Length; ++i)
{
var _value = arr[i];
if (_value.CompareTo(value) > 0)
{
value = _value;
i_Pos = i;
}
}
return value;
}
测试例如下:
int[] arr = { 2, 31, 148, 754, 9143, 0, 4548149, 645, 2, 54 };
Console.WriteLine("Index={0}, Value={1}, Type={2}",MaxIndex(arr),MaxValue(arr), MaxValue(arr).GetType());
DateTime[] days = { DateTime.Parse("2019-10-11"), DateTime.Parse("2010-10-11"), DateTime.Parse("2019-10-11 00:00:00") };//, DateTime.Parse("2020-01-11") };
Console.WriteLine("Index={0}, Value={1}, Type={2}", MaxIndex(days), MaxValue(days), MaxValue(days).GetType());
string[] name = { "asdfg", "asdasda", "asda", "wa", "z" };
Console.WriteLine("Index={0}, Value={1}, Type={2}", MaxIndex(name), MaxValue(name), MaxValue(name).GetType());
测试结果为:
同样地,你也可以写出一个求最小值的函数。
完整VS示例如下:
using System;
namespace ConsoleApp_Test
{
class Program
{
//传入一个数组,求出一个数组的最大值的位置
public static int MaxIndex<T>(T[] arr) where T : IComparable<T>
{
var i_Pos = 0;
var value = arr[0];
for (var i = 1; i < arr.Length; ++i)
{
var _value = arr[i];
if (_value.CompareTo(value) > 0)
{
value = _value;
i_Pos = i;
}
}
return i_Pos;
}
//传入一个数组,求出一个数组的最大值
public static T MaxValue<T>(T[] arr) where T : IComparable<T>
{
var i_Pos = 0;
var value = arr[0];
for (var i = 1; i < arr.Length; ++i)
{
var _value = arr[i];
if (_value.CompareTo(value) > 0)
{
value = _value;
i_Pos = i;
}
}
return value;
}
static void Main(string[] args)
{
// 定义一个数组
int[] arr = { 2, 31, 148, 754, 9143, 0, 4548149, 645, 2, 54 };
Console.WriteLine("Index={0}, Value={1}, Type={2}",MaxIndex(arr),MaxValue(arr), MaxValue(arr).GetType());
DateTime[] days = { DateTime.Parse("2019-10-11"), DateTime.Parse("2010-10-11"), DateTime.Parse("2019-10-11 00:00:00") };//, DateTime.Parse("2020-01-11") };
Console.WriteLine("Index={0}, Value={1}, Type={2}", MaxIndex(days), MaxValue(days), MaxValue(days).GetType());
string[] name = { "asdfg", "asdasda", "asda", "wa", "z" };
Console.WriteLine("Index={0}, Value={1}, Type={2}", MaxIndex(name), MaxValue(name), MaxValue(name).GetType());
Console.ReadKey();
}
}
}