You could try SortedDictionary. If you call .Keys on it, you will get a sorted collection of keys back. You can then use the LINQ .First() function to get the first key in the collection, for example:
var mySortedDictionary = new SortedDictionary<float, int>();
// ...
// Add some values to dictionary
// ...
// Note, you will need the System.Linq namespace for First()
float firstKey = mySortedDictionary.Keys.First();
int firstValue = mySortedDictionary[firstKey];
// If you just need the value:
int firstValue2 = mySortedDictionary.Values.First();
If you needed to get a key other than the first or last one, you can use the LINQ .ToArray() or .ToList() functions to return an indexable array or list, like so:
float[] indexableKeys = mySortedDictionary.Keys.ToArray();
int[] indexableValues = mySortedDictionary.Values.ToArray();
Additionally, the following code will iterate through the collection and give you all of the KeyValuePairs in sorted order:
foreach (var pair in mySortedDictionary)
{
int key = pair.Key;
// Do stuff with key...
object value = pair.Value;
// Do stuff with value...
}
As an alternative, you could also use SortedList, which is indexable. To use this, you would just need the following code:
var mySortedList = new SortedList<float, int>();
// ...
// Add some values to sortedlist
// ...
int firstValue = mySortedList.Values[0];
Note: I haven't had a chance to benchmark either of these, so I'm not sure which would perform better. Using a sorted collection definitely has more overhead than a regular one. If you only need to know which key is the first one, you may be best off creating a custom class that contains a Dictionary and a private field private float first;
that stores which key is the first one. When you add to that class, it adsd teh KeyValuePair to the dictionary and checks to see if the key is smaller than your first
variable (or if there are no keys in the dictionary). If so, it sets first
to the new key. When you remove a value, you again would remove it from the Dictionary. If the key is equal to your first
value, then you'd need to sort the Dictionary.Keys collection and find the new first. This would probably perform the best, but you would have to write the class yourself.
Note: After doing some benchmarks, I found that SortedDictionary is faster for removal, but SortedList is faster for adding and indexing by key. This was done by populating a regular dictionary with 1,000,000 keyValue pairs (keys were shuffled so that they'd be entered in random order). I then:
- Added each of those pairs to both sorted collections
- Performed a lookup on each key in both sorted collections
- Removed each pair by calling Remove(Key) on both sorted collections
SortedList was about twice as fast when adding or indexing, but took about 1000 times the amount of time to remove each element.