在排序的对象映射中交换值

Swapping values in a sorted object map

假设我有一个排序字典,其键被反对

public class ExecutionMap 
{
    protected SortedDictionary<object, object> ExecutionMap { get; set; }
}

假设我在该地图中有一个对象,我想将它的位置与下一个交换:

public void SwapUp(object key) 
{
    
    value = ExecutionMap.Get(key);
    //How do I do I swap with the one that comes before it 
}

将它与之前的交换的有效方法是什么? 我宁愿不必枚举字典来找到它之前的键

您可以使用来自第三方的 C5.TreeDictionary<K,V> 而不是 SortedDictionary<K,V> C5 library. This type offers rich functionality regarding finding previous and next entries, finding ranges of entries, supports backward enumeration etc. All these operations are implemented efficiently on top of a red-black tree set. Comparatively the functionality offered by the native SortedDictionary<K,V> 相当差,不足以实现您想要实现的目标。

public class ExecutionMap
{
    protected C5.TreeDictionary<object, object> ExecutionMap { get; set; }

    public void SwapUp(object key)
    {
        // Find the entry with this key
        if (ExecutionMap.Find(ref key, out var value))
        {
            // Find the entry that comes before it
            if (ExecutionMap.TryPredecessor(key, out var predecessor))
            {
                // Create a key that is smaller than the key of the predecessor
                // Creating a suitable key may be tricky
                var newKey = CreateSmallerKey(predecessor.Key);

                // Swap the key of the stored value
                // An exception will be thrown if the newKey already exists
                ExecutionMap.Add(newKey, value);
                bool removed = ExecutionMap.Remove(key);
                Debug.Assert(removed);
            }
        }
    }
}