I need a data structure that can sort objects by the float keys they're associated with, lowest first. The trouble is that the keys represent cost so there are often duplicates, I don't care about this because if two have the same cost I'll just grab the first as it makes no difference, the problem is that the compiler complains.
Is there a data structure that behaves in the same way but allows duplicate keys?
EDIT - I still need the duplicates though because if one turns out to be a dead-end, I grab the next (they're nodes in an a* search)
so just to be clear, it needs to allow duplicate keys that are sorted in order.
In SortedDictionary, the key must be unique. Duplicate keys are not allowed. In SortedDictionary, the keys are immutable and cannot be null. In SortedDictionary, the value can be null when the type of the value is of reference type.
A dictionary does not keep the items sorted by the keys, so the structure you are looking for is actually not equivalent to a Dictionary at all. What you want is something similar to a SortedList or SortedDictionary except that it should allow duplicate keys. No such class exists in .
In short: The easiest way to go would be a generic List<T> collection while skiping the ArrayList class. Because, there are some performance considerations that you need to take into account. In addition, you can also use List<KeyValuePair<string,int>> . This will store a list of KeyValuePair 's that can be duplicate.
You write:
equivalent to a dictionary that allows duplicate keys
I need a data structure that can sort objects by the float keys they're associated with, lowest first.
A dictionary does not keep the items sorted by the keys, so the structure you are looking for is actually not equivalent to a Dictionary
at all. What you want is something similar to a SortedList
or SortedDictionary
except that it should allow duplicate keys.
No such class exists in .NET. However you have a few options:
SortedDictionary<double, List<TValue>>
if you want to store all the values associated for a key, even though you usually only need the first. When inserting a key for the first time, create a new list and add the value to the list. When inserting a key that already exists, fetch the list and append the value to the list.SortedDictionary<double, TValue>
and check for duplicates before inserting. Only the first value for each key will be stored, so unlike the above approach, you can't access the second value at all with this method.Related
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With