Skip to content

Instantly share code, notes, and snippets.

@jackmott
Last active March 24, 2017 02:32
Show Gist options
  • Select an option

  • Save jackmott/980d96e3dcff3086a5a95d88e1f11246 to your computer and use it in GitHub Desktop.

Select an option

Save jackmott/980d96e3dcff3086a5a95d88e1f11246 to your computer and use it in GitHub Desktop.
Handy way to do minby / maxby extension methods in C# 7
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