首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >交换排序对象映射中的值

问交换排序对象映射中的值
EN

Stack Overflow用户
提问于 2021-03-03 09:40:57
回答 1查看 34关注 0票数 1

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

代码语言:javascript
复制
public class ExecutionMap 
{
    protected SortedDictionary<object, object> ExecutionMap { get; set; }
}

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

代码语言:javascript
复制
public void SwapUp(object key) 
{
    
    value = ExecutionMap.Get(key);
    //How do I do I swap with the one that comes before it 
}

有什么有效的方法来交换这个和之前的那个呢?我不希望在查找关键字之前必须枚举字典。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-03-03 17:50:27

您可以使用第三方C5库中的C5.TreeDictionary<K,V>,而不是SortedDictionary<K,V>。这种类型提供了丰富的功能,包括查找前一个和下一个条目、查找条目范围、支持向后枚举等。所有这些操作都是在红黑树集合的顶部高效实现的。相比之下,原生SortedDictionary提供的功能相当差,并且不足以实现您试图实现的目标。

代码语言:javascript
复制
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);
            }
        }
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66449542

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档