- Home /
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
Answer by whydoidoit · Sep 17, 2012 at 08:23 PM
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.
ah, cool, thank you! I'll try implementing this shortly.
Your answer
Follow this Question
Related Questions
How to alphabetically sort your List? 2 Answers
SQLite Sort and or List Sort 1 Answer
How to "get" an item from an ArrayList? 0 Answers
Add a Play Next Song And A shuffle Option To Music Player C# 1 Answer