Skip to content

Instantly share code, notes, and snippets.

@leventeren
Created October 6, 2020 20:29
Show Gist options
  • Save leventeren/bbd259af8a9fb4af20924dee994c10be to your computer and use it in GitHub Desktop.
Save leventeren/bbd259af8a9fb4af20924dee994c10be to your computer and use it in GitHub Desktop.
using UnityEngine;
using System.Collections.Generic;
using System;
public static class CollectionHelper
{
public delegate bool FindHandler<T>(T item);
public delegate TKey SelectHandler<TSource, TKey>(TSource source);
public static void OrderBy<T, TKey>(T[] array, SelectHandler<T, TKey> handler)
where TKey : IComparable<TKey>
{
for (int i = 0; i < array.Length - 1; 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;
}
}
public static void OrderByDescending<T, TKey>(T[] array, SelectHandler<T, TKey> handler)
where TKey : IComparable
{
for (int i = 0; i < array.Length - 1; 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;
}
}
public static T Find<T>(T[] array, FindHandler<T> handler)
{
foreach (var item in array)
{
if (handler(item))
return item;
}
return default(T);
}
public static T[] FindAll<T>(T[] array, FindHandler<T> handler)
{
List<T> tempList = new List<T>();
foreach (var item in array)
{
if (handler(item))
tempList.Add(item);
}
return tempList.Count > 0 ? tempList.ToArray() : null;
}
public static TKey[] Select<T, TKey>(T[] array,
SelectHandler<T, TKey> handler)
{
TKey[] tempArr = new TKey[array.Length];
for (int i = 0; i < array.Length; i++)
{
tempArr[i] = handler(array[i]);
}
return tempArr;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment