Skip to content

Instantly share code, notes, and snippets.

@leventeren
Created October 6, 2020 20:27
Show Gist options
  • Save leventeren/ce79bec7b31be5132777975b65936cf4 to your computer and use it in GitHub Desktop.
Save leventeren/ce79bec7b31be5132777975b65936cf4 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
class ArrayHelper
{
static public void OrderBy<T, TKey>(T[] array, SelectHandler<T, TKey> handler)
where TKey : IComparable,IComparable<TKey>
{
for (int i = 0; i < array.Length - 1; i++)
{
for (int j = i + 1; j < array.Length; j++)
{ //arrar[i]: int[],string[],Student[]>zs.age
//if (array[i].CompareTo(array[j]) > 0)
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, IComparable<TKey>
{
for (int i = 0; i < array.Length - 1; i++)
{
for (int j = i + 1; j < array.Length; j++)
{ //arrar[i]: int[],string[],Student[]>zs.age
//if (array[i].CompareTo(array[j]) > 0)
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, IComparable<TKey>
{
//T max = default(T);
T max = array[0];
for (int i = 1; i < array.Length ; i++)
{
if (handler(max).CompareTo(handler(array[i])) < 0)
{
max = array[i];
}
}
return max;
}
static public T Min<T, TKey>(T[] array, SelectHandler<T, TKey> handler)
where TKey : IComparable, IComparable<TKey>
{
//T max = default(T);
T min = array[0];
for (int i = 1; i < array.Length; i++)
{
if (handler(min).CompareTo(handler(array[i])) > 0)
{
min = array[i];
}
}
return min;
}
static public T Find<T>(T[] array, FindHandler<T> handler)
{
T t = default(T);
for (int i = 0; i < array.Length; i++)
{
if (handler(array[i]))
{
t = array[i];
break;
}
}
return t;
}
static public T[] FindAll<T>(T[] array, FindHandler<T> handler)
{
List<T> list = new List<T>();
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;
}
}
delegate TKey SelectHandler<T,TKey>(T t);//T Student Id,Age,Tall,Name,Book
delegate bool FindHandler<T>(T t);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment