Last active
March 24, 2017 02:32
-
-
Save jackmott/980d96e3dcff3086a5a95d88e1f11246 to your computer and use it in GitHub Desktop.
Handy way to do minby / maxby extension methods in C# 7
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public static (T obj, float value) MinBy<T>(this T[] array,Func<T,float> lambda) | |
| { | |
| float minValue = float.MaxValue; | |
| T minT = default(T); | |
| //note if you implement this for List<T>, don't use foreach, it is slower. Use a for loop. | |
| foreach (var t in array) | |
| { | |
| var value = lambda.Invoke(t); | |
| if (value < minValue) | |
| { | |
| minValue = value; | |
| minT = t; | |
| } | |
| } | |
| return (minT, minValue); | |
| } | |
| //use example: | |
| var (closestMine,mineDist) = | |
| world.ironMines.MinBy(mine => Vector2.DistanceSquared(mine.pos, player.pos)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment