- Home /
How do you sort a dictionary by value?
There are a lot of resources on google, but none of them seem to work. It doesn't let me use a SortedDictionary either.
I'm trying to get an index of a list of GameObjects, and assign their GetDistanceFromPlayer return value as the value of the dictionary. Then I want to sort it and use the values to make a new list of GameObjects with the distance sorted from lowest to highest. I'm obviously not asking you to write my code for me, but it would be great to get an actual functional function I can use to at least start in the right direction.
Seems to me you won't need a dictionary at all if you sorted the list directly using the GetDistanceFromPlayer-method.
@Jamora So it's possible to sort a list of GameObjects by one of their members?
Yes, as long as the members can be meaningfully compared to each other.
You cant really compare two GameObjects, but you could compare e.g. their transform's x-position. When doing that, you just need to remember which member is part of which GameObject.
yes, you can sort a single list of GameObjects with the .Sort function of List:
List<GameObject> objList = new List<GameObject>();
//Fill with gameobjects...
objList.Sort((x,y) => GetDistanceFromPlayer(x).ComareTo(GetDistanceFromPlayer(y));
$$anonymous$$eep in $$anonymous$$d that this is not the most efficient way because it will call the function GetDistanceFromPlayer multiple times for each gameObject.
@GameVortex How would I go about comparing the distance variable in your example? Isn't your example assu$$anonymous$$g that the GetDistanceFromPlayer variable is contained within the class sorting the list?
Answer by GameVortex · Nov 14, 2013 at 06:13 PM
This is a general way of sorting a list of CustomClass based on a custom variable in the class:
List<CustomClass> list = new List<CustomClass>();
//Fill with objects of CustomClass...
list.Sort((x,y) => x.CustomIntVariable.ComareTo(y.CustomIntVariable));
Answer by TonyLi · Nov 14, 2013 at 02:55 PM
If you really need to use a dictionary (and not a SortedList as @Jamora suggests), try this: http://stackoverflow.com/a/291
foreach ($$anonymous$$eyValuePair<int,float> item in ActiveCrabs.OrderBy(key=> ActiveCrabs[key].GetComponent<CrabScript>().DistanceFromPlayer))
{
// do something with item.$$anonymous$$ey and item.Value
}
It's not working. What am I doing wrong?
You solved? where you adding this in the header of your script?
System.Linq
After more than two years I imagine he's probably forgotten all about it :p
Just want to point out that sorting is usaully overkill on a Dictionary. The whole point is to use the key to look things up. If you want a SortedList, you could just use it directly rather than incurring the overhead of a Dictionary.