unity数组查找助手类

unity数组查找助手类

使用,泛型,委托,数组等进行排序,查找等方法,代码的通用性很高,有不足的地方还希望大佬们给点建议
//这里主要进行理解委托以及函数参数的意思
//委托就是一个数据类型
//第一个参数是数组,第二个参数是一个朗姆达表达式
public delegate TKey SelectHandler<T, TKey>(T t);
public delegate bool FindHandler(T t);
public static class ArrayHelper
{
///
/// 升序排列
///
/// 数据类型
/// 数据类型中属性的
/// 数据类型对象的数组
/// 委托对象用于从某个类型中选取某个字段并且返回该字段的数值
///
static public void OrderBy<T, TKey>
(T[] array, SelectHandler<T, TKey> handler)
where TKey : IComparable
{
for (int i = 0; i < array.Length; i++)
{
for (int j = i + 1; j < array.Length; j++)
{
//handler(array[j])调用委托返回一个需要进行比较的属性
if (handler(array[i]).CompareTo(handler(array[j])) > 0)
{
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
}
///
/// 降序排序
///
/// 数据类型
/// 数据类型字段的类型
/// 数据类型对象的数组
///
/// 委托对象:负责 从某个类型中选取某个字段 返回这个字段的值
///
static public void OrderByDescending<T, TKey>
(T[] array, SelectHandler<T, TKey> handler)
where TKey : IComparable
{
for (int i = 0; i < array.Length; i++)
{
for (int j = i + 1; j < array.Length; j++)
{
if (handler(array[i]).CompareTo(handler(array[j])) < 0)
{
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
}
///
/// 返回最大的
///
/// 数据类型
/// 数据类型字段的类型
/// 数据类型对象的数组
///
/// 委托对象:负责 从某个类型中选取某个字段 返回这个字段的值
///
static public T Max<T, TKey>
(T[] array, SelectHandler<T, TKey> handler)
where TKey : IComparable
{
T temp = default(T);//进行初始化
temp = array[0];
for (int i = 1; i < array.Length; i++)
{
if (handler(temp).CompareTo(handler(array[i])) < 0)
{
temp = array[i];
}
}
return temp;
}
///
/// 返回最小的
///
/// 数据类型
/// 数据类型字段的类型
/// 数据类型对象的数组
///
/// 委托对象:负责 从某个类型中选取某个字段 返回这个字段的值
///
static public T Min<T, TKey>
(T[] array, SelectHandler<T, TKey> handler)
where TKey : IComparable
{
T temp = default(T);
temp = array[0];
for (int i = 1; i < array.Length; i++)
{
if (handler(temp).CompareTo(handler(array[i])) > 0)
{
temp = array[i];
}
}
return temp;
}
//实现数组工具类的 通用的查找的方法 Find
static public T Find(T[] array, FindHandler handler)
{
T temp = default(T);
for (int i = 0; i < array.Length; i++)
{
if (handler(array[i]))
{
return array[i];
}
}
return temp;
}
//查找所有的方法 FindAll
//给定一个查找的条件? 返回满足条件的所有的
static public T[] FindAll(T[] array, FindHandler handler)
{
List list = new List();
for (int i = 0; i < array.Length; i++)
{
if (handler(array[i]))
{
list.Add(array[i]);
}
}
return list.ToArray();
}
//选择:选取数组中对象的某些成员形成一个独立的数组
static public TKey[] Select<T, TKey>(T[] array, SelectHandler<T, TKey> handler)
{
TKey[] keys = new TKey[array.Length];
for (int i = 0; i < array.Length; i++)
{
keys[i] = handler(array[i]);
}
return keys;
}
}

猜你喜欢

转载自blog.csdn.net/weixin_43333566/article/details/94762951