Is it possible to sort an array determined by an external comparison?

I’d like to sort through List, and compare each member of the list to an external variable.
I’ve looked at the sort() function, but it appears as if all comparisons must occur within the List.

Is it possible to somehow compare each member of the list to an external variable and sort the list based on that?

in pseudocode (sorry for the completely incorrect syntax, I don’t know how to use sort() yet), I’d like to do something like:

List<myCustomClass> everything = new List<myCustomClass>
GameObject targetObject;

function delegate compareDistances(listItem.transform.location, externalObject.transform.location){
  Vector3 distance = (listItem.transform.location - externalObject.transform.location)
  return distance;
}
   

everything.sort(compareDistances(listItem, targetObject);

thanks in advance

Well there are two ways - you can write a class that implements IComparable or you can use Linq.

I’m a bit of a Linq fan - so here’s how to do it that way:

import System.Linq;

...


var sortedList = everything.OrderBy(function(thing) { return (thing.transform.position - externalObject.transform.position).sqrMagnitude; }).ToList();

Using sqrMagnitude rather than distance will yield the same sort order, but executes faster.