这里我们类实现一些简单数组的功能
1 所有的类型都适用
2 使用方便,易操作
功能包括
1 排序
2 查找满足条件的数据类型
3 查最小值和最大值
4 得到某些数据的一维数据类型
代码如下(自行参考)
using System;
using System.Collections.Generic;
public class ArrayHelper
{
//排序1
public static void Sort<T>(T[] array) where T : IComparable<T>
{
for (int i = 0; i < array.Length; i++)
for (int j = i + 1; j < array.Length; j++)
{
if (array[i].CompareTo(array[j]) > 0)
{
T tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
}
}
//排序2
public static void Sort<T>(T[] array, IComparer<T> comparer)
{
for (int i = 0; i < array.Length; i++)
for (int j = i + 1; j < array.Length; j++)
{
if (comparer.Compare(array[i], array[j]) > 0)
{
T tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
}
}
//排序3
public delegate int Comparison<T>(T a, T b);
public static void Sort<T>(T[] array, Comparison<T> comparison)
{
for (int i = 0; i < array.Length; i++)
for (int j = i + 1; j < array.Length; j++)
{
if (comparison(array[i], array[j]) > 0)
{
T tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
}
}
public delegate TKey SelectHandler<T, TKey>(T select);
//最大值的数据查找
public static T Max<T, TKey>(T[] arr, SelectHandler<T, TKey> select)
where TKey : IComparable<TKey>
{
if (arr.Length == 0) return default;
T res = arr[0];
for (int i = 1; i < arr.Length; i++)
{
if (select(arr[i]).CompareTo(select(res)) > 0)
{
res = arr[i];
}
}
return res;
}
//最小值的数据查找
public static T Min<T, TKey>(T[] arr, SelectHandler<T, TKey> select)
where TKey : IComparable<TKey>
{
if (arr.Length == 0) return default;
T res = arr[0];
for (int i = 1; i < arr.Length; i++)
{
if (select(arr[i]).CompareTo(select(res)) < 0)
{
res = arr[i];
}
}
return res;
}
//得到某些数据的一维数组
public static TKey[] SelectMember<T, TKey>(T[] arr, SelectHandler<T, TKey> select)
{
TKey[] keys = new TKey[arr.Length];
for (int i = 0; i < arr.Length; i++)
{
keys[i] = select(arr[i]);
}
return keys;
}
public delegate bool FindHandler<T>(T x);
//查找满足条件第一个的数据
public static T Find<T>(T[] arr, FindHandler<T> find)
{
for (int i = 0; i < arr.Length; i++)
{
if (find(arr[i])) return arr[i];
}
return default;
}
//查找满足条件的所有的数据
public static T[] FindAll<T>(T[] arr, FindHandler<T> find)
{
List<T> list = new();
for (int i = 0; i < arr.Length; i++)
{
if (find(arr[i]))
{
list.Add(arr[i]);
}
}
return list.ToArray();
}
}
方便以后的数组处理,还是很好用滴