- Home /
What good is a SortedList if GetKey doesn't work?
I first assumed "mySortedList[0]" would return the first list item, but that was wrong. The right way to say that is "mySortedList.GetKey(0)," but doing that gives me the error- 'GetKey' is not a member of 'System.Collections.Generic.SortedList.'. What? The .net documentation says it is. So how else am I going to find out what the first (= largest) value is, which is the whole point of having a sorted list?
the first way is the correct way. mySortedList[0] will return the first item. Were you getting an error or something?
Yes. "mySortedList[0]" is trying to give me the value with the key 0 and giving this error:
$$anonymous$$eyNotFoundException: The given key was not present in the dictionary.
Systems.Collections.Generic.SortedList`2[System.Single.System.Int32].get_Item (Single key)
Answer by whydoidoit · Jun 12, 2012 at 02:12 PM
You can use Linq and do
using System.Linq;
...
var value = mySortedList.Values.First(); // The first value
or
var key = mySortedList.Keys.First();
Thanks, $$anonymous$$ike- though I had just figured it out anyway: I can do mySortedList.Values[0] or mySortedList.$$anonymous$$eys[0]. Is there an advantage to using Linq here?
Actually only on a dictionary which doesn't have the indexer properties. Just one point, inserting into a SortedList is costly - whereas using Linq let's you do stuff similarly on an unsorted list or to create a sorted list from an unsorted one:
var sorted = unsortedArrayOrList.OrderBy(e=>e.someSortableValue).ToList();
This is faster if you add items and then need to sort.
Your answer
![](https://koobas.hobune.stream/wayback/20220613072631im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Error with script. 1 Answer
Expression denotes a `type', where a `variable', `value' or `method group' was expected 2 Answers
"Takes `2' arguments" 2 Answers
Cannot implicitly convert type 'int' to 'UnityEngine.Vector3' 3 Answers